admin管理员组文章数量:1357666
I'm wondering if it is possible to use a jQuery deferred object to test whether or not an element is in the 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.
Thanks!
I'm wondering if it is possible to use a jQuery deferred object to test whether or not an element is in the 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.
Thanks!
Share Improve this question asked Jan 31, 2013 at 2:48 tvpmbtvpmb 1,4772 gold badges13 silver badges18 bronze badges 3-
This looks wrong
if $(selector) {
... Why using a deferred? What are you trying to do? – elclanrs Commented Jan 31, 2013 at 2:53 - Deferreds are to do with responding to the progress and pletion asynchronous tasks, but I don't perceive any asynchronicity in the scenario described above. – Beetroot-Beetroot Commented Jan 31, 2013 at 3:17
- Thanks for your responses. I missed one key piece, the problem is the DOM element gets injected asynchronously. Appreciate the answer "Explosion Pills" :-) – tvpmb Commented Jan 31, 2013 at 16:40
3 Answers
Reset to default 8I 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; you can just use .done
on the deferred object directly.
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
if($(selector).length > 0) {
// do something
}
$(selector) return an array of elements that match the condition of selector.
本文标签: javascriptHow do I check if an element is in the DOM using a jquery deferred objectStack Overflow
版权声明:本文标题:javascript - How do I check if an element is in the DOM using a jquery deferred object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744069025a2585545.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论