How to keep checking for new
  • elements in a

    2019-07-30 00:42发布

  • 问题:

    I want to keep checking for new li elements so that whenever there will be these new elements ,I would be getting new alerts?

    JS:

    $(function () {
    
        if ($('#div').find('<li></li>')) {
            alert('you just got new <li> elements');
        }
    
        // it is just an examplory function which                       
        // will keep looking for only  new <li> elements created by ol list
    
    })(); 
    

    Js fiddle is here http://jsfiddle.net/younis764/rWcKu/3/

    Please help.

    回答1:

    A function like this should help you

    document.addEventListener("DOMNodeInserted", function(event){
      var element = event.target;
      if (element.tagName == 'li') {
         alert("li added");    
      }
    });
    

    Check Mutation events

    FIDDLE DEMO

    HTML

    <div id="container" style="background-color:#e0d0a0; width:300px; height:100px;"></div>   
    <button onclick="AddLiToContainer ();">Add a li node to the container!</button>
    

    JAVASCRIPT

     function AddLiToContainer() {
         var newLi = document.createElement("li");
         var textNode = document.createTextNode("Hello World");
         newLi.appendChild(textNode);
         if (newLi.addEventListener) {
             newLi.addEventListener('DOMNodeInserted', OnNodeInserted, false);
         }
    
         var container = document.getElementById("container");
         container.appendChild(newLi);
     }
    
     function OnNodeInserted(event) {
         var Li = event.target;
         alert("The text node '" + Li.innerHTML + "' has been added to an element.");
     }