我试图将一个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();
Run Code Online (Sandbox Code Playgroud)
但是一旦我$('.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'));
Run Code Online (Sandbox Code Playgroud)
我读到你不能将参数传递给setTimeout函数,所以我试图将元素作为附加参数传递给setTimeout调用,例如setTimout(checkIfElementsExist, 500, elements);,但仍然没有.
更新:
我已经做了Pointy提到的更新,但它似乎仍然不起作用.这是一个更好地说明问题的JSFIDDLE.
代替
setTimeout(checkIfElementsExist, 500);
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
setTimeout(function( ) { checkIfElementsExist(".myElements"); }, 500);
Run Code Online (Sandbox Code Playgroud)
通过在实际函数周围包装匿名函数,您可以传入您想要的任何参数.