javascript:在IE中getElementById问题 [英] javascript: getElementById problem in IE

查看:83
本文介绍了javascript:在IE中getElementById问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用JavaScript将单击事件附加到复选框。下面显示的是HTML和JS。

 <!DOCTYPE HTML PUBLIC -  // W3C // DTD HTML 4.01 Transitional / / EN> 
< html>
< head>
< title>< / title>
< meta http-equiv =Content-Typecontent =text / html; charset = UTF-8>
< / head>
< body>
< input type =hiddenname =caution_cvalue =0>
< input type =checkboxid =caution_cname =caution_cvalue =1tabindex =120>
< script type =text / javascript>
var cb = document.getElementById('caution_c');
cb.onclick = function(){
alert(1);
}
< / script>
< / body>
< / html>

问题是,在IE中,click事件不会触发。我已经缩小了问题的位置。问题是在复选框之前有一个隐藏的输入,并且这两个元素具有相同的名称。我不知道为什么这会导致问题(毕竟,我使用getElementById,而隐藏的元素甚至没有id)。



有没有此外,有没有一个很好的解决方法(我可以做 document.getElementsByName('caution_c')[1] ,但我不想...)

解决方案

Internet Explorer对 name 和 id - 强烈建议将这两个属性视为相同。



您可以通过以下方式解决问题:1)确保文档中没有id / name冲突,或者2)覆盖IE的本地getElementById方法



在此处阅读更多内容


I am trying to attach a click event to a check box using JavaScript. Shown below is the HTML and 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).

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...)

解决方案

Internet Explorer gets confused over name and id - it is highly recommended to treat these two attributes as if they were the same.

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.

Read more about it here.

这篇关于javascript:在IE中getElementById问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆