Internet Explorer 中的 jquery show()/hide() 问题?

标签 jquery internet-explorer

以下 html 代码在 Firefox 中有效,但由于某种原因在 IE 中失败(Label2 未显示)。这是一个错误还是我错过了什么?

如有任何帮助,我们将不胜感激。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript">
        </script>
        <script>
            jQuery(document).ready(function(){
                function setVis(){
                    var val = $("#check").is(":checked");
                    if (val) 
                        $("#g_1").show();
                    else 
                        $("#g_1").hide();
                }

                setVis();
                $("#check").change(setVis);
            });
        </script>
    </head>
    <body>
        <span>
            <input type="checkbox" id="check" />
            <label>Label1</label>
        </span>
        <span id="g_1">
            <label>Label2</label>
        </span>
    </body>
</html>

最佳答案

原因:

根据 MSDN,change event

...fired when the contents are committed and not while the value is changing. For example, on a text box, this event is not fired while the user is typing, but rather when the user commits the change by leaving the text box that has focus.

复选框的行为类似:在 IE 中,直到焦点从元素上移除后,事件才会触发(尝试一下:单击复选框,然后按 Tab 键关闭,行为符合预期)。 Firefox 显然不尊重这种区别。

解决方案:

使用click事件处理程序而不是change:

            $("#check").click(setVis);

...并且跨浏览器的行为应该一致。

关于Internet Explorer 中的 jquery show()/hide() 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/368807/

相关文章:

javascript - 如何在 Javascript/JQuery 或 AngularJS 中清除浏览器缓存

css - Cufon 在 IE 中不工作——一个 CSS 问题

javascript - 显示单词的代码,JS Jquery

javascript - 如何将通过 Javascript 添加的表行发布到 ASP.NET 中的服务器?

javascript - CSS/jQuery 性能 - 提供更高分辨率的选择器是否更好

javascript - 我可以通过 jQuery 创建脚本标签吗?

javascript - IE 8 无效参数错误

jQuery:一个可排序列表,在另一个列表上显示结果

forms - HTML 表单 "placeholder"在 IE 8 中不工作

javascript - 如何禁用 JavaScript 错误消息?