如何使用jquery deferred对象检查DOM中的元素?

时间:2021-06-30 08:40:50

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 deferred对象来测试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!

谢谢!

3 个解决方案

#1


7  

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; you can just use .done on the deferred object directly.

请注意,$。当不需要;你可以直接对递延对象使用。done。

#2


2  

You can use the following to check if an element exists.
You don't have to use deferred.

您可以使用以下命令检查元素是否存在。你不需要使用deferred。

if( jQuery(selector).length > 0 ) {
    // exists
}

#3


0  

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.

$(选择器)返回匹配选择器条件的元素数组。

#1


7  

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; you can just use .done on the deferred object directly.

请注意,$。当不需要;你可以直接对递延对象使用。done。

#2


2  

You can use the following to check if an element exists.
You don't have to use deferred.

您可以使用以下命令检查元素是否存在。你不需要使用deferred。

if( jQuery(selector).length > 0 ) {
    // exists
}

#3


0  

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.

$(选择器)返回匹配选择器条件的元素数组。