Nam*_*one 6 html javascript jquery
我正在尝试使用MutationObserver来检查在表中添加的新行,我在下面得到的代码似乎适用于H2元素,但是当我将其更改为Table行时,console.log不输出到控制台,如果我检查表,则正在添加TR.有没有人有任何想法?我无法弄清楚为什么它不会观察到表格行被添加
var list = document.getElementById("testtable");
var MutationObserver = window.MutationObserver ||
window.WebKitMutationObserver ||
window.MozMutationObserver;
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList') {
console.log("mutation!");
}
});
});
observer.observe(list, {
attributes: true,
childList: true,
characterData: true
});
var element = ("tr");
setInterval(
function(){
$(list).append("<h2>" + "THIS IS A TEST" + "</h2>");
//This doesn't work
//$(list).append("<tr>" + "<td>" + "<h2>" + "THIS IS A TEST" + "</h2>" + "</td>" + "</tr>");
},
2000);
Run Code Online (Sandbox Code Playgroud)
这是一个工作小提琴:http://jsfiddle.net/ggwb2ejy/
您需要将该subtree选项设置为true
observer.observe(list, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
Run Code Online (Sandbox Code Playgroud)
当你添加一个tr它没有直接添加到table它被添加到一个tbody元素,所以实际上一个被观察元素的子树被修改.要观察您需要subtree: true在配置中设置的子树中的任何更改
演示:小提琴