[英]How do I check if an element is in the DOM using a jquery deferred object?
I'm wondering if it is possible to use a jQuery deferred object to test whether or not an element is in the DOM. 我想知道是否可以使用jQuery延迟对象来测试元素是否在DOM中。
Here's kind of what I'm thinking: 这就是我在想的:
function chkDOM(selector) {
if $(selector) {
return deferred.promise();
}
}
$.when(chkDOM(selector)).then(function() {
// do something
});
I don't exactly know how to form the code to make this happen, but I hope that my question makes sense. 我不知道如何形成代码来实现这一点,但我希望我的问题是有道理的。 If I can get this piece to work right, then I can essentially delay the calling of certain jquery plugins so that they actually run properly. 如果我可以让这个工作正常工作,那么我基本上可以延迟调用某些jquery插件,以便它们实际运行正常。
Thanks! 谢谢!
I assume that you are running a loop that periodically checks the existence of the selector: 我假设你正在运行一个循环,定期检查选择器的存在:
var dfd = $.Deferred();
var checkSelector = setInterval(function () {
if ($("#selector").length) {
dfd.resolve();
clearInterval(checkSelector);
}
}, 1000);
dfd.done(function () {
console.log('it has been added');
});
Note that $.when
is not needed; 请注意,不需要$.when
; you can just use .done
on the deferred object directly. 你可以直接在延迟对象上使用.done
。
You can use the following to check if an element exists. 您可以使用以下内容检查元素是否存在。
You don't have to use deferred. 您不必使用延期。
if( jQuery(selector).length > 0 ) {
// exists
}
To check element in DOM, just use 要检查DOM中的元素,只需使用
if($(selector).length > 0) {
// do something
}
$(selector) return an array of elements that match the condition of selector. $(selector)返回与selector的条件匹配的元素数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.