javascript: IE 中的 getElementById 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3708373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript: getElementById problem in IE
提问by Gaurav Sharma
I am trying to attach a click event to a check box using JavaScript. Shown below is the HTML and JS.
我正在尝试使用 JavaScript 将单击事件附加到复选框。下面显示的是 HTML 和 JS。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<input type="hidden" name="caution_c" value="0">
<input type="checkbox" id="caution_c" name="caution_c" value="1" tabindex="120">
<script type="text/javascript">
var cb = document.getElementById('caution_c');
cb.onclick = function() {
alert(1);
}
</script>
</body>
</html>
The problem is that in IE, the click event does not fire. I have narrowed down the problem location. The issue is that there is a hidden input just before the check box and both these elements have the same name. I'm not sure why this is causing a problem(after all, I'm using getElementById and the hidden element does not even have an id).
问题是在 IE 中,单击事件不会触发。我已经缩小了问题的位置。问题在于复选框之前有一个隐藏的输入,并且这两个元素具有相同的名称。我不确定为什么这会导致问题(毕竟,我使用的是 getElementById 并且隐藏元素甚至没有 id)。
Is there a valid reason for this type of behavior (IE only. Works fine in Firefox...as always :( )? Also, is there a good workaround (I could just do document.getElementsByName('caution_c')[1]but I don't want to...)
这种类型的行为是否有正当理由(仅限 IE。在 Firefox 中工作正常......一如既往:()?另外,是否有一个好的解决方法(我可以只做document.getElementsByName('caution_c')[1]但我不想……)
回答by Magnar
Internet Explorer gets confused over nameand id- it is highly recommended to treat these two attributes as if they were the same.
Internet Explorer中迷糊了name和id-强烈推荐,好像他们是相同的对待这两个属性。
You can fix it either by 1) ensure that there are no id/name conflicts in your document, or 2) override IE's native getElementById-method.
您可以通过 1) 确保文档中没有 id/name 冲突,或 2)覆盖 IE 的本机 getElementById-method来修复它。
回答by Ben
Try using a different event such as onchangeor onfocusto see if that solves it. Also I don't think onclickwill be fired if a user tabs onto the checkbox, which may or not be how you intend it to work.
尝试使用不同的事件,例如onchange或onfocus以查看是否可以解决问题。此外,我认为onclick如果用户点击复选框,这可能是或不是您打算如何工作,我认为不会被解雇。
回答by parth joshi
I agree, IE is poor in understanding things at html level.
I would rather add the link to button rather than using anchor elements, as IE is having trouble at anchor level with document.getElementById(). Try same at button and will work for other users.
我同意,IE 在理解 html 级别的东西方面很差。我宁愿将链接添加到按钮而不是使用锚元素,因为 IE 在锚级别使用document.getElementById(). 在按钮上尝试相同的方法,适用于其他用户。

