将jQuery对象传递到setTimeout递归函数中

Passing jQuery object into setTimeout recursive function

本文关键字:setTimeout 递归函数 jQuery 对象      更新时间:2023-09-26

我试图将jQuery对象传递到setTimout函数中,但没有成功。

这就是我目前拥有的-它正在工作:

var checkIfElementsExist = function () {
    var elements = $('.myElements');
    if (elements.length) {
        console.log('els are here!');
        $(window.document).trigger('elementsExist', [elements]);
    } else {
        console.log('nope, check it again');
        setTimeout(checkIfElementsExist, 500);
    }
}
checkIfElementsExist();

但是,一旦我将$('.myElements')从函数中取出,并尝试将其作为参数传递到函数中,elements.length总是返回零。

var checkIfElementsExist = function (elements) {
    if (elements.length) {
        console.log('els are here!');
        $(window.document).trigger('elementsExist', [elements]);
    } else {
        console.log('nope, check it again');
        setTimeout(checkIfElementsExist, 500);
    }
}
checkIfElementsExist($('.myElements'));

我读到您不能将参数传递到setTimeout函数中,所以我尝试将元素作为附加参数传递到setTimeout调用中,例如setTimout(checkIfElementsExist, 500, elements);,但仍然没有。

更新:

我已经做了Pointy提到的更新,但它似乎仍然不起作用。这里有一个JSFIDDLE来更好地说明这个问题。

而不是

    setTimeout(checkIfElementsExist, 500);

你可以这样做:

    setTimeout(function( ) { checkIfElementsExist(".myElements"); }, 500);

通过将一个匿名函数包装在实际函数中,您可以传递任何您想要的参数。

执行$('.myElements')遍历DOM并返回一个包含class="myElements"的所有元素的数组。

当您最初通过$('.myElements')时,您只是第一次构造该数组。以下过程中,您没有传递任何参数。

这里真正的问题是,为什么在加载脚本时.myElements没有加载?它们是动态创建的吗?如果没有,您的脚本应该封装在$(document).ready(function(){ // ... code here })中,等待加载整个页面。