这是用于侦听子列表 of 上的突变#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
无论是作为孩子或更深的后裔(如孙子)。