Javascript 将jQuery对象传递给setTimeout递归函数

Javascript 将jQuery对象传递给setTimeout递归函数,javascript,jquery,Javascript,Jquery,我试图将jQuery对象传递到setTimout函数中,但没有效果 这就是我目前拥有的——它正在发挥作用: var checkIfElementsExist = function () { var elements = $('.myElements'); if (elements.length) { console.log('els are here!'); $(window.document).trigger('elementsExist',

我试图将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')
并尝试将其作为参数传递到函数中,
元素.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提到的更新,但似乎仍然不起作用。下面是一个更好地说明问题的示例。

而不是

    setTimeout(checkIfElementsExist, 500);
您可以这样做:

    setTimeout(function( ) { checkIfElementsExist(".myElements"); }, 500);
通过将匿名函数包装在实际函数周围,您可以传入所需的任何参数。

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

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


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

setTimeout(function(){checkIfElementsExist(elements);},500)也:
setTimeout('checkIfElementsExist(elements)'500)。谢谢你的回答。我已经更新了我的代码,但它似乎仍然不能正常工作。我已经做了一个例子来帮助说明这个问题。@Blexy因为您只构造了一次jQuery对象,所以当DOM更改时它不会更新。啊!!因此,缓存选择器,然后在后续检查中,引用缓存的选择器。非常感谢。