【问题标题】:jQuery attribute selector not working in Internet ExplorerjQuery 属性选择器在 Internet Explorer 中不起作用
【发布时间】:2015-05-13 00:41:12
【问题描述】:

在我的 JavaScript 中,我使用 css 选择器 [style="display:none"] 并且代码可以在 Chrome、Firefox、Opera 和 Safari(在 Windows 上)按预期工作。

但是在 Internet Explorer(第 11 版)中,不幸的是,它工作时出错了。

用于测试:
只需单击 Chrome 中的按钮(例如#visible_elements_count),然后单击 Internet Explorer 中的按钮。您将体验到不同的返回值。

HTML:

<section>
    <ul>
        <li>visible Element</li>
        <li style="display:none">invisible Element</li>
        <li>visible Element</li>
    </ul>
</section>

<button id="all_elements_count">all elements</button>
<button id="visible_elements_count">visible elements</button>
<button id="invisible_elements_count">invisible elements</button>

<!-- JAVASCRIPTS -->
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    $("#all_elements_count").click(function () {
        var counter = $("section ul li").length;
        alert(counter);
    });

    $("#visible_elements_count").click(function () {
        var counter = $("section ul li:not([style='display:none'])").length;
        alert(counter);
    });

    $("#invisible_elements_count").click(function () {
        var counter = $("section ul li[style='display:none']").length;
        alert(counter);
    });
</script>

来源: 我阅读了所有内容about selectors!仍然无法解决这个问题。

感谢任何帮助!

【问题讨论】:

标签: jquery css internet-explorer jquery-selectors


【解决方案1】:

你应该使用 jQuery :visible & :hidden 伪选择器:

var counter = $("section ul li:visible").length;

var counter = $("section ul li:hidden").length;

要获得更好的性能,请参阅@Jai 的回答。

【讨论】:

    【解决方案2】:

    您应该使用:hidden, :visible.filter()

        $("#all_elements_count").click(function () {
            var counter = $("section ul li").length;
            alert(counter);
        });
    
        $("#visible_elements_count").click(function () {
            var counter = $("section ul li").filter(':visible').length;
            alert(counter);
        });
    
        $("#invisible_elements_count").click(function () {
            var counter = $("section ul li").filter(':hidden').length;
            alert(counter);
        });
    

    【讨论】:

    • 这成功了!你能解释一下为什么使用 JQuery 属性选择器 [style='display:none'] 会导致错误吗?
    • @stylesenberg 在使用属性时,IE 的行为可能会有所不同。我想这就是它可能在 IE 中实现的方式。
    猜你喜欢
    • 2011-01-25
    • 1970-01-01
    • 2011-03-24
    • 2015-12-08
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 2012-06-07
    相关资源
    最近更新 更多