jQuery .not() 函数不起作用

jQuery .not() function not working

本文关键字:函数 不起作用 not jQuery      更新时间:2023-09-26

我最近遇到了.not((函数的问题,这是代码:

var interval = setInterval(function() {
        $('.test').not('.updated').each(function(){
                var $parentDiv = $('.test').parent('div');
                // do something
                parentDiv.find('.test').addClass("updated"); 
                //Above: change this element's status
        });
}, 3000);

问题是:有时当元素 $('.test'( 谁有类 'update' 也在循环中。

我的想法:这意味着 not(( 选择器不起作用?

所以我想知道代码的真正问题是什么?

您的代码正在查找具有类"test"的所有元素,然后排除那些也具有类"更新"的元素。

然后,对于其中每个元素,您正在执行另一个.find()操作以查找具有类"test"的元素。但是,这不包括.not()调用,因此,如果您有一个元素将类"test"嵌套在另一个元素中,则无论它是否已经具有类"更新",它都会受到影响。

我认为您的代码真的应该像这样:

var interval = setInterval(function() {
        $('.test').not('.updated').addClass("updated");
}, 3000);

您不需要.each(),因为.addClass()会为您执行此操作。

编辑 — 如果你确实需要在.each()内做更多的工作,你的代码将如下所示:

var interval = setInterval(function() {
        $('.test').not('.updated').each(function(){
                var $parentDiv = $(this).parent('div');
                // do something
                $(this).addClass("updated"); 
                //Above: change this element's status
        });
}, 3000);

.each()回调中,this将绑定到外部 jQuery 序列中的每个选定元素:具有类"test"但没有类"update"的元素集。 如果您在.each()回调中再次使用 $(".test"),它将重新开始并在整个页面中找到所有带有类"test"的元素。

这是您更新的函数,它应该使用 $(this) 而不是在每个循环中$('.test')

var interval = setInterval(function() {
        $('.test').not('.updated').each(function(){
                var $parentDiv = $(this).parent('div');
                // do something
                $(this).addClass("updated"); 
                //Above: change this element's status
        });
}, 3000);

当您在每个$('.test')中引用哪个是所有测试类.updated否则,这就是.updated类仍然出现在循环中的原因

您正在使用用于选择该元素的所有后代的.find()

参考 .find((

因此,在您的情况下,方案是没有类的类.test .updated将搜索其所有子类以查找类.test,并将类updated添加到其中。因此,所有的孩子,无论他们是否.updated上课,.updated班级都会被添加到其中。

因此,您可以通过以下方式简单地实现您想要做的事情:

 $('.test').not('.updated').each(function(){
   $(this).addClass("updated");
 });

或者为什么不简单地,

$('.test').not('.updated').addClass('updated');