38

我正在尝试在创建特定 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 的等价物?我尝试了 attrchange.js,在 DOM 元素的样式对象更改后,您可以使用 javascript 钩子触发器吗?但是该插件仅检测元素何时被修改,而不是何时创建。

4

3 回答 3

33

这是监听子列表中的突变#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作为子更深的后代(例如孙子)。

于 2012-11-07T21:17:13.993 回答
8

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

不要忘记, , 的第二个参数.observe()MutationObserverInit重要:

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

文档

  • childListtrue如果要观察目标节点的子元素(包括文本节点)的添加和删除,则设置为。
  • subtreetrue如果要观察目标和目标后代的突变,则设置为。
于 2018-03-31T02:04:56.387 回答
-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

于 2021-01-10T13:02:55.777 回答