不断检查是否存在某些事情并做某事

时间:2022-03-11 22:38:05

The content on my page is loaded via AJAX (it's a step by step process) and I need to check if a specific div exists.

我页面上的内容是通过AJAX加载的(这是一步一步的过程),我需要检查是否存在特定的div。

That specific div appears after few clicks. I have to mention that I don't know the number of clicks.

点击几下后就会显示该特定div。我必须提到我不知道点击次数。

How can I continuously check if the div exists till it finds it and after it finds it do to something?

我怎样才能连续检查div是否存在,直到它找到它并且在它发现它做什么之后?

Later edit: How can I continuously check till a specific div doesn't exist and do something after that. More exactly the div is there, but after a few ajax calls it gets removed.

稍后编辑:如何连续检查,直到某个特定的div不存在,然后再做一些事情。更确切地说div就在那里,但经过一些ajax调用后它就被删除了。

5 个解决方案

#1


1  

If you can't control the AJAX load, this might be a solution for you.

如果您无法控制AJAX负载,这可能是您的解决方案。

Use DOMSubtreeModified event, which will allow any method, click or what ever, to add (or remove) content and it will be detected.

使用DOMSubtreeModified事件,它将允许任何方法,单击或任何方式添加(或删除)内容,它将被检测到。

(function(doc,found) {
  window.addEventListener('DOMSubtreeModified', function() {

    var yourdiv = doc.querySelector("#yourdiv");

    if(found && !yourdiv){
      // Was there but is gone, do something
      found = false;

    }

    if(yourdiv){
      // Found it, do something
      found = true;

    }

  }, false);
})(document,false);

It work like this, when content is inserted (or removed) the event fires and check for your specific div.

它的工作方式如下,当插入(或删除)内容时,事件将触发并检查您的特定div。

It also has benefits of not being called every nn second, like a timer, nor being processed on every click, only when DOM changed.

它还具有不会被称为计时器的每nn秒被调用的好处,也不会在每次点击时被处理,只有当DOM改变时。


As commented by @metarmask, DOMSubtreeModified is deprecated but has still a better cross browser coverage than the newer MutationObserver.

正如@metarmask评论的那样,DOMSubtreeModified已被弃用,但仍然比新的MutationObserver有更好的跨浏览器覆盖率。

An equivalent sample using the newer method would be

使用较新方法的等效样本将是

(function(doc,found) {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {

          var yourdiv = doc.querySelector("#yourdiv");

          if(found && !yourdiv){
            // Was there but is gone, do something
            found = false;

          }

          if(yourdiv){
            // Found it, do something
            found = true;

          }

        });
    });
    observer.observe(doc, { childList: true, subtree: true });
})(document,false);

#2


1  

Use setInterval:

使用setInterval:

var divCheckingInterval = setInterval(function(){
    // Find it with a selector
    if(document.querySelector("#element")){
        console.log("Found!");
        clearInterval(divCheckingInterval);
        // Do something
    }
}, 500);

A better way to do something when the div appears using MutationObservers:

使用MutationObservers显示div时更好的方法:

var observer = new MutationObserver(function(mutations){
    mutations.forEach(function(mutation){
        for(var i = 0;i < mutation.addedNodes.length;i++){
            if(mutation.addedNodes[i].id === "the-element"){
                console.log("Found!");
                observer.disconnect();
                // Do something
            }
        }
    });
});
observer.observe(document.querySelector("#parent-of-where-the-div-is-going-to-appear"), {childList: true, subtree: true});

The function in the MutationObserver constructor will only get triggered when a element is added or removed from the element you specified which is better for performance.

MutationObserver构造函数中的函数只有在从您指定的元素添加或删除元素时才会被触发,这样可以提高性能。

#3


0  

If it happens after a certain number of clicks you can monitor after every click on the page.

如果在一定次数的点击后发生,您可以在每次点击页面后进行监控。

function checkIfDivExists () {
  if (document.querySelector('#your-div')) {
    // Stop monitoring
    document.removeEventListener('click', checkIfDivExists);
    // Do what you need to do
  }
}

document.addEventListener('click', checkIfDivExists)

In this way you check only when it's necessary rather than trying several times each second, which will slow down the page.

通过这种方式,您只需在必要时进行检查,而不是每秒尝试多次,这将减慢页面速度。

#4


0  

Use setInterval to periodically check for your div (500 ms below). When its found, take the action and remember to clear the interval.

使用setInterval定期检查你的div(下面500毫秒)。当它找到时,采取行动并记住清除间隔。

t = setInterval(function(){
    var mydiv = $('div.myclass');
    if (mydiv.length > 0) {
        console.log('Div exists');
        clearInterval(t);
    }
}, 500);

#5


0  

var time = setInterval(check, 100);

check = function()
{
    if ($("div").length > 0 )
    {
        //do something
        clearInterval (time); // clear countdown
    }
}

#1


1  

If you can't control the AJAX load, this might be a solution for you.

如果您无法控制AJAX负载,这可能是您的解决方案。

Use DOMSubtreeModified event, which will allow any method, click or what ever, to add (or remove) content and it will be detected.

使用DOMSubtreeModified事件,它将允许任何方法,单击或任何方式添加(或删除)内容,它将被检测到。

(function(doc,found) {
  window.addEventListener('DOMSubtreeModified', function() {

    var yourdiv = doc.querySelector("#yourdiv");

    if(found && !yourdiv){
      // Was there but is gone, do something
      found = false;

    }

    if(yourdiv){
      // Found it, do something
      found = true;

    }

  }, false);
})(document,false);

It work like this, when content is inserted (or removed) the event fires and check for your specific div.

它的工作方式如下,当插入(或删除)内容时,事件将触发并检查您的特定div。

It also has benefits of not being called every nn second, like a timer, nor being processed on every click, only when DOM changed.

它还具有不会被称为计时器的每nn秒被调用的好处,也不会在每次点击时被处理,只有当DOM改变时。


As commented by @metarmask, DOMSubtreeModified is deprecated but has still a better cross browser coverage than the newer MutationObserver.

正如@metarmask评论的那样,DOMSubtreeModified已被弃用,但仍然比新的MutationObserver有更好的跨浏览器覆盖率。

An equivalent sample using the newer method would be

使用较新方法的等效样本将是

(function(doc,found) {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {

          var yourdiv = doc.querySelector("#yourdiv");

          if(found && !yourdiv){
            // Was there but is gone, do something
            found = false;

          }

          if(yourdiv){
            // Found it, do something
            found = true;

          }

        });
    });
    observer.observe(doc, { childList: true, subtree: true });
})(document,false);

#2


1  

Use setInterval:

使用setInterval:

var divCheckingInterval = setInterval(function(){
    // Find it with a selector
    if(document.querySelector("#element")){
        console.log("Found!");
        clearInterval(divCheckingInterval);
        // Do something
    }
}, 500);

A better way to do something when the div appears using MutationObservers:

使用MutationObservers显示div时更好的方法:

var observer = new MutationObserver(function(mutations){
    mutations.forEach(function(mutation){
        for(var i = 0;i < mutation.addedNodes.length;i++){
            if(mutation.addedNodes[i].id === "the-element"){
                console.log("Found!");
                observer.disconnect();
                // Do something
            }
        }
    });
});
observer.observe(document.querySelector("#parent-of-where-the-div-is-going-to-appear"), {childList: true, subtree: true});

The function in the MutationObserver constructor will only get triggered when a element is added or removed from the element you specified which is better for performance.

MutationObserver构造函数中的函数只有在从您指定的元素添加或删除元素时才会被触发,这样可以提高性能。

#3


0  

If it happens after a certain number of clicks you can monitor after every click on the page.

如果在一定次数的点击后发生,您可以在每次点击页面后进行监控。

function checkIfDivExists () {
  if (document.querySelector('#your-div')) {
    // Stop monitoring
    document.removeEventListener('click', checkIfDivExists);
    // Do what you need to do
  }
}

document.addEventListener('click', checkIfDivExists)

In this way you check only when it's necessary rather than trying several times each second, which will slow down the page.

通过这种方式,您只需在必要时进行检查,而不是每秒尝试多次,这将减慢页面速度。

#4


0  

Use setInterval to periodically check for your div (500 ms below). When its found, take the action and remember to clear the interval.

使用setInterval定期检查你的div(下面500毫秒)。当它找到时,采取行动并记住清除间隔。

t = setInterval(function(){
    var mydiv = $('div.myclass');
    if (mydiv.length > 0) {
        console.log('Div exists');
        clearInterval(t);
    }
}, 500);

#5


0  

var time = setInterval(check, 100);

check = function()
{
    if ($("div").length > 0 )
    {
        //do something
        clearInterval (time); // clear countdown
    }
}