我试图在创建特定 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");
});
是否有使用突变观察器的等效方法?我尝试了 attrchange.js 上的特色DOM 元素的样式对象更改后可以触发 javascript 钩子吗? https://stackoverflow.com/questions/10868104/但该插件仅检测元素何时被修改,而不是何时创建。
这是监听子列表中突变的代码#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
作为一个孩子or更深的后代(例如孙子)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)