用于创建新元素的Mutation Observer

时间:2012-11-07 19:57:50

标签: javascript jquery mutation-observers dom4

我正在尝试在创建特定div时使函数关闭。用最简单的术语来说,我有类似的东西:

<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>

之前,我有突变事件听取div#bar的创建 - 这样的事情:

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

是否有使用Mutation Observers的等价物?我尝试了Can you have a javascript hook trigger after a DOM element's style object changes?上的attrchange.js,但该插件仅检测元素何时被修改,而不是在创建时。

3 个答案:

答案 0 :(得分:29)

这是侦听#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
});

但是,这只会观察#foo。如果您希望将#bar添加为其他节点的新子节点,则需要通过额外调用obs.observe()来观察这些潜在父节点。要观察ID为baz的节点,您可以执行以下操作:

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

添加subtree选项意味着观察者会将#bar添加为子更深的后代(例如孙子)。

答案 1 :(得分:5)

使用jQuery时,可以简化MutationObserver s的使用,如下所示。

$("#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>

值得注意的是,.observe()MutationObserverInit的第二个参数非常重要:

如果childList: true仅作为直接子项添加,请在选项中使用spansubTree: true如果它可以低于#canvas以下的任何级别。

来自docs

  • childList:如果要观察目标节点的子元素(包括文本节点)的添加和删除,则设置为true
  • subtree:如果要观察目标和目标后代的突变,请设置为true

答案 2 :(得分:-1)

突变观察者

// 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