简体   繁体   English

用于创建新元素的 Mutation Observer

[英]Mutation Observer for creating new elements

I am trying to make a function go off when a particular div is created.我试图在创建特定的 div 时关闭一个函数。 In the simplest of terms, I have something like this:用最简单的术语来说,我有这样的东西:

<a href="" id="foo">Click me!</a>
<script>
$("#foo").live("click",function(e) {
    e.preventDefault();
    $(this).append($("<div />").html("new div").attr("id","bar"));
});
</script>

Before, I had mutation events listen for the creation of div#bar - something like this:之前,我有突变事件监听 div#bar 的创建——像这样:

$("#bar").live("DOMNodeInserted", function(event) {
    console.log("a new div has been appended to the page");
});

Is there an equivalent using Mutation Observers?是否有使用 Mutation Observers 的等价物? I tried attrchange.js featured on Can you have a javascript hook trigger after a DOM element's style object changes?我尝试了 attrchange.js在 DOM 元素的样式对象更改后你有一个 javascript 钩子触发器吗? but that plugin only detects when an element has been modified, not when it's created.但是该插件仅检测元素何时被修改,而不是何时创建。

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.这段代码侦听#foo的子列表上的变化,并检查是否添加了 id 为bar的子列表。

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

$("#foo").live("click",function(e) {
    e.preventDefault();
    $(this).append($("<div />").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<mutations.length; ++i) {
        // look through all added nodes of this mutation
        for(var j=0; j<mutations[i].addedNodes.length; ++j) {
            // was a child added with ID of 'bar'?
            if(mutations[i].addedNodes[j].id == "bar") {
                console.log("bar was added!");
            }
        }
    }
});

// have the observer observe foo for changes in children
obs.observe($("#foo").get(0), {
  childList: true
});

However, this only observes #foo .但是,这只会观察#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() .如果你想寻找#bar作为其他节点的新子节点的添加,你需要通过额外调用obs.observe()来观察那些潜在的父节点。 To observe a node with the id of baz , you might do:要观察 ID 为baz的节点,您可以这样做:

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 (eg grandchild). subtree选项的添加意味着观察者将寻找#bar的添加作为孩子更深的后代(例如孙子)。

When using jQuery, the usage of MutationObserver s can be simplified as shown below.使用 jQuery 时,可以简化MutationObserver的用法,如下所示。

 $("#btnAddDirectly").click(function () { $("#canvas").append($('<span class="stuff">new child direct</span>')); }); $("#btnAddAsChildOfATree").click(function () { $("#canvas").append($('<div><div><span class="stuff">new child tree</span></div></div>')); }); var obs = new MutationObserver(function(mutations, observer) { // using jQuery to optimize code $.each(mutations, function (i, mutation) { var addedNodes = $(mutation.addedNodes); var selector = "span.stuff" var filteredEls = addedNodes.find(selector).addBack(selector); // finds either added alone or as tree filteredEls.each(function () { // can use jQuery select to filter addedNodes alert('Insertion detected: ' + $(this).text()); }); }); }); var canvasElement = $("#canvas")[0]; obs.observe(canvasElement, {childList: true, subtree: true});
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="canvas"> Canvas </div> <button id="btnAddDirectly">Add span directly to canvas</button> <button id="btnAddAsChildOfATree">Add span as child of a tree</button>

Don't forget, the second argument to .observe() , MutationObserverInit , is important:不要忘记, .observe()的第二个参数MutationObserverInit很重要:

In the options, use childList: true if the span will only be added as a direct child.在选项中,使用childList: true如果span将仅作为直接子项添加。 subTree: true if it can be at any level down below #canvas . subTree: true如果它可以在#canvas以下的任何级别,则为 true。

From the docs :文档

  • childList : Set to true if additions and removals of the target node's child elements (including text nodes) are to be observed. childList :如果要观察目标节点的子元素(包括文本节点)的添加和删除,则设置为true
  • subtree : Set to true if mutations to target and target's descendants are to be observed. subtree :如果要观察目标和目标的后代的突变,则设置为true

Mutation Observer变异观察者

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

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

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    // Use traditional 'for loops' for IE 11
    for(const 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
const observer = new MutationObserver(callback);

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

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

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM