用于创建新元素的Mutation Observer [英] Mutation Observer for creating new elements

查看:147
本文介绍了用于创建新元素的Mutation Observer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to make a function go off when a particular div is created. 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>

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

Before, I had mutation events listen for the creation of div#bar - something like this:

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

是否有使用Mutation Observers的等价物?我尝试了在DOM元素的样式对象发生变化后你有一个javascript钩子触发器吗?但是该插件只能检测到的attrchange.js当一个元素被修改时,而不是在它被创建时。

Is there an equivalent using Mutation Observers? I tried attrchange.js featured on Can you have a javascript hook trigger after a DOM element's style object changes? but that plugin only detects when an element has been modified, not when it's created.

推荐答案

这是监听<$子列表上的突变的代码c $ c> #foo 并检查是否添加了身份 bar 的孩子。

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.

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 的节点,您可以执行以下操作:

However, this only observes #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(). To observe a node with the id of baz, you might do:

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

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

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 (e.g. grandchild).

这篇关于用于创建新元素的Mutation Observer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆