Mutation Observer for creating new elements

前端 未结 2 798
眼角桃花
眼角桃花 2020-11-29 22:29

I am trying to make a function go off when a particular div is created. In the simplest of terms, I have something like this:

C         


        
2条回答
  •  天涯浪人
    2020-11-29 22:52

    This is code that listens for mutations on the childlist of #foo and checks to see if a child with the id of bar is added.

    MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
    
    $("#foo").live("click",function(e) {
        e.preventDefault();
        $(this).append($("
    ").html("new div").attr("id","bar")); }); // define a new observer var obs = new MutationObserver(function(mutations, observer) { // look through all mutations that just occured for(var i=0; i

    However, this only observes #foo. If you want to look for the addition of #bar as a new child of other nodes, you need to observe those potential parents with additional calls to obs.observe(). To observe a node with the id of baz, you might do:

    obs.observe($('#baz').get(0), {
      childList: true,
      subtree: true
    });
    

    The addition of the subtree option means that the observer will look for the addition of #bar as either a child or a deeper descendant (e.g. grandchild).

提交回复
热议问题