我想执行一个函数时,一些div或输入被添加到html。 这可能吗?

例如,添加了一个文本输入,然后应该调用函数。


当前回答

下面的例子改编自Mozilla Hacks的博客文章,并使用MutationObserver。

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

浏览器支持:Chrome 18+, Firefox 14+, IE 11+, Safari 6+

其他回答

下面的例子改编自Mozilla Hacks的博客文章,并使用MutationObserver。

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

浏览器支持:Chrome 18+, Firefox 14+, IE 11+, Safari 6+

使用TrackChanges来检测html更改。 链接:https://www.npmjs.com/package/track-changes-js

例子

 let button = document.querySelector('.button');

 trackChanges.addObserver('buttonObserver', () => button);
 
 trackChanges.addHandler('buttonObserver', buttonHandler);

 function buttonHandler(button) {
   console.log(`Button created: ${button}`);
 }

在2022年发现了这个问题的解决方案。

我们已经看到了不同的解决方案,主要涉及MutationObserver。

如果有人想记录DOM更改并存储它们以便一段时间后重播,他们可以使用rrweb

编辑:

再举个例子,下面是一些提示:

rrweb您可以通过CDN或npm使用

让我们以CDN为例来记录DOM更改事件:

步骤1:只需在<HTML><head>标签中包含以下脚本标签

<script src="https://cdn.jsdelivr.net/npm/rrweb@2.0.0-alpha.2/dist/rrweb-all.js" crossorigin="anonymous"></script> .js

步骤2:并在代码中添加以下代码以捕获rrweb生成的事件。

<script>
var events = [];
rrweb.record({
    emit(event) {
       events.push(event);
       // you can store this event anywhere and you can replay them later. ex: some JSON file, or DB
    }
});

</script>

这个例子主要用于记录任何web应用程序的事件。

如需详细了解(如何录制/回放),请参阅rrweb文档。

重播的例子:

这是为了调试,但添加在这里,以便任何人都可以检查重放的一面:

重复的例子

或者你可以简单地创建你自己的事件,到处运行

 $("body").on("domChanged", function () {
                //dom is changed 
            });


 $(".button").click(function () {

          //do some change
          $("button").append("<span>i am the new change</span>");

          //fire event
          $("body").trigger("domChanged");

        });

完整的示例 http://jsfiddle.net/hbmaam/Mq7NX/

使用MutationObserver界面,如Gabriele Romanato的博客所示

找到了,Chrome 18+,火狐14+

// 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();