简体   繁体   English

setTimeout()函数在jQuery each()函数中不起作用

[英]setTimeout() function doesn't work inside of jQuery each() function

I want to apply code to a series of matched elements with a delay between each. 我想将代码应用于一系列匹配的元素,每个元素之间都有延迟。 I don't understand why the following code doesn't work: 我不明白为什么以下代码不起作用:

        jQuery(".myElement").each(function() {
            setTimeout(function() {
                jQuery(this).remove();
            }, 1000);
        });

I know there's been similar questions asked, but the answers haven't worked for me. 我知道有人问过类似的问题,但答案对我没有用。 I understand that this code is simultaneously applying the delays to each matched element, which isn't what I want. 我知道这段代码将延迟同时应用于每个匹配的元素,这不是我想要的。 But I still can't figure out how to make it work. 但是我仍然不知道如何使它工作。

No need for .each 不需要.each

setTimeout(function() {
    jQuery(".myElement").remove();
}, 1000);

The reason for now working is because this no longer refers to the element in each -- you could set a context variable, but since you're just removing the elements anyway, just do it in one swoop! 现在开始工作的原因是因为this不再引用each元素-您可以设置上下文变量,但是由于您无论如何都只是删除元素,因此只需一键即可!

JSBIN DEMO JSBIN演示

Your issue lies in the fact that you are invoking jQuery(this).remove() and passing the return value of this to your setTimeout. 您的问题在于您正在调用jQuery(this).remove()并将this的返回值传递给setTimeout。 The assumption is that you are intending for this to run when the timeout expires. 假设您打算在超时到期时运行它。 If that is the case, you need to wrap this in a function, so that function will be passed to setTimeout and executed when the timer expires. 如果是这种情况,则需要将其包装在一个函数中,以便将该函数传递给setTimeout并在计时器到期时执行。

jQuery('.myElement').each(function() {
    var thiz = jQuery(this);
    setTimeout(function() { thiz.remove(); }, 1000);
})

Thanks for the answers. 感谢您的回答。 For whatever reason, I couldn't get either of them to work. 无论出于什么原因,我都无法让他们中的任何一个工作。 This code, however, ended up doing the job for me: 但是,这段代码最终为我完成了这项工作:

jQuery(".element").each( function(e) {
    var element = jQuery(this);
    setTimeout(function () {
        jQuery(element).remove();
    }, e*1000);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM