Detect changes in the DOM

后端 未结 7 2323
温柔的废话
温柔的废话 2020-11-21 05:45

I want to execute a function when some div or input are added to the html. Is this possible?

For example, a text input is added, then the function should be called.<

7条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 05:53

    Use the MutationObserver interface as shown in Gabriele Romanato's blog

    Chrome 18+, Firefox 14+, IE 11+, Safari 6+

    // The node to be monitored
    var target = $( "#content" )[0];
    
    // Create an observer instance
    var observer = new MutationObserver(function( mutations ) {
      mutations.forEach(function( mutation ) {
        var newNodes = mutation.addedNodes; // DOM NodeList
        if( newNodes !== null ) { // If there are new nodes added
            var $nodes = $( newNodes ); // jQuery set
            $nodes.each(function() {
                var $node = $( this );
                if( $node.hasClass( "message" ) ) {
                    // do something
                }
            });
        }
      });    
    });
    
    // Configuration of the observer:
    var config = { 
        attributes: true, 
        childList: true, 
        characterData: true 
    };
    
    // Pass in the target node, as well as the observer options
    observer.observe(target, config);
    
    // Later, you can stop observing
    observer.disconnect();
    

提交回复
热议问题