jQuery Not选择器导致无限循环

时间:2009-09-11 17:44:09

标签: jquery selector

以下代码导致我的浏览器崩溃。对于Firefox,我已经给了一个选项,无论我是否想要停止jQuery,因为它的运行时间比它应该的长。

div id="divLeaving">
    You are about to leave to: <span id="spanLeavingURL"></span>
    <a id="divLeavingYes" href="#">Yes</a><a id="divLeavingNo" href="#">No</a>
</div>
<a href="http://www.google.com">google</a>

<script type="text/javascript" language="javascript">

    $(document).ready(function() {
        $("a:not(#divLeavingYes, #divLeavingNo)").click(function() {
            var url = $(this).attr("href");
            var test_if_local = url.indexOf("mycompany.com");
            if (test_if_local == -1) {
                $("#spanLeavingURL").text(url);
                $("#divLeavingYes").attr("href", url);
                $("#divLeavingNo").click(function() { $(this).dialog('destroy'); });
                $("#divLeaving").dialog({ modal: true });
                return false;
            }
        });
    });
</script>

但是,如果我删除not选择器,它不会使我的浏览器崩溃。

<div id="divLeaving">
    You are about to leave to: <span id="spanLeavingURL"></span>
    <a id="divLeavingYes" href="#">Yes</a><a id="divLeavingNo" href="#">No</a>
</div>
<a href="http://www.google.com">google</a>

<script type="text/javascript" language="javascript">

    $(document).ready(function() {
        $("a").click(function() {
            var url = $(this).attr("href");
            var test_if_local = url.indexOf("mycompany.com");
            if (test_if_local == -1) {
                $("#spanLeavingURL").text(url);
                $("#divLeavingYes").attr("href", url);
                $("#divLeavingNo").click(function() { $(this).dialog('destroy'); });
                $("#divLeaving").dialog({ modal: true });
                return false;
            }
        });
    });
</script>

如何更改查询以便选择除#divLeavingYes和#divLeavingNo以外的所有内容?

3 个答案:

答案 0 :(得分:1)

我不了解jQuery的实现,但是:

a:not(#divLeavingYes, #divLeavingNo)

不是有效的CSS3选择器。 :not选择器只能使用simple selector。尝试:

a:not(#divLeavingYes):not(#divLeavingNo)

答案 1 :(得分:0)

试试这个,我包括“event.stopPropagation();”:

$(document).ready(function() {
    $("a:not(#divLeavingYes, #divLeavingNo)").click(function(event) {
    event.stopPropagation();
        var url = $(this).attr("href");
        var test_if_local = url.indexOf("mycompany.com");
        if (test_if_local == -1) {
            $("#spanLeavingURL").text(url);
            $("#divLeavingYes").attr("href", url);
            $("#divLeavingNo").click(function() { $(this).dialog('destroy'); });
            $("#divLeaving").dialog({ modal: true });
            return false;
        }
    });
});

答案 2 :(得分:0)

我不确定你的HTML是如何构建的,但也许你可以通过jQuery的slice()过滤器来实现这个技巧......

http://docs.jquery.com/Traversing/slice