我有以下结构:
<div class="wrapper">
<div class="col">left</div>
<div class="col">middle</div>
<div class="col">right</div>
</div>
现在我想要仅在INSIDE $('。col')包含类“block”的div时才获取节点,如:
是的,这是:
$('.col')[1].append($('<div class="block">urgent</div>'));
但是这个没有:
$('.col')[1].append($('<div class="different">dontcare</div>'));
我的观察者看起来像这样:
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
for (var i = 0; i < mutation.addedNodes.length; i++) {
console.log(mutation.addedNodes[i]);
}
});
});
observer.observe(document, {
childList: true,
subtree:true,
characterData:true,
attributes:true
});
我在Chrome扩展程序中,但这不应该真正重要
答案 0 :(得分:3)
修改了你的代码:
$('.col')[1].append
抛出一个TypeError,因为你在DOM Node上使用jQuery函数,使用eq
,ethod for
,添加forEach
我在.block
NodeList中添加了对mutation.addedNodes
元素的检查
addedNode.classList.contains('block')
$(function () {
'use strict';
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
[].slice.call(mutation.addedNodes).forEach(function (addedNode) {
if (addedNode.classList.contains('block')) {
console.log("I'm has a class block, whats next?");
}
});
});
});
observer.observe(document, {
childList: true,
subtree:true,
characterData:true,
attributes:true
});
//Yes
$('.col').eq(1).append($('<div class="block">urgent</div>'));
//No
$('.col').eq(1).append($('<div class="different">dontcare</div>'));
});