How can I detect when a new element has been added to the document in jquery?

前端 未结 10 1364
猫巷女王i
猫巷女王i 2020-12-01 21:29

How can I detect when a new element has been added to the document in jquery ?

Explanation: I want to know when an element with class \"column-header\" has been adde

10条回答
  •  春和景丽
    2020-12-01 21:38

    I think the DOMNodeInserted method mentioned above is probably the sexiest choice, but if you need something that is going to work with IE8 and lower, you could do something like the following:

    // wrap this up in en immediately executed function so we don't 
    // junk up our global scope.
    (function() {
       // We're going to use this to store what we already know about.
       var prevFound = null;
    
       setInterval(function() {
          // get all of the nodes you care about.
          var newFound = $('.yourSelector');
    
          // get all of the nodes that weren't here last check
          var diff = newFound.not(prevFound);
    
          // do something with the newly added nodes
          diff.addClass('.justGotHere');
    
          // set the tracking variable to what you've found.
          prevFound = newFound;
       }, 100);
    })();
    

    That is just the basic idea, you can change that however you want, make a method out of it, keep the return value of the setInterval so you can stop it, or whatever you need to do. But it should get the job done.

提交回复
热议问题