Mri*_*lla 5 javascript dom mutation-observers
我发现 MutationObserver 文档相当混乱。我想观察文档主体何时将具有该类的 DIV 元素superelement添加到 DOM。
<div class="superelement" style="display:none;2"></div>
Run Code Online (Sandbox Code Playgroud)
我已经设法将这段代码粘合在一起:
const observer = new MutationObserver(onMutation);
observer.observe(document, {
childList: true,
subtree: true,
});
function onMutation(mutations) {
const found = [];
for (const { addedNodes } of mutations) {
for (const node of addedNodes) {
if (!node.tagName) {
continue; // not an element
} else {
if (node.classList.contains('superelement')) {
console.log(node)
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
是否没有更干净的方法来迭代所有添加的元素?我可以想象这相当慢。
在我找到一些不完全混乱的东西之前,我进行了一些搜索。你实际上只需要做两件事;当你有干净的代码可以使用时,事情就会容易得多。
对于第一个对象,当满足条件(在本例中:)时,MutationObserver对象将传递一个MutationRecord对象和一个对象(没有第三个参数):MutationObserver{childList: true}
const observer = new MutationObserver(function(mutation_record,mutation_observer)
{
//Match your condition here:
if (mutation_record[0] && mutation_record[0].addedNodes[0] && mutation_record[0].addedNodes[0] === id_('modal'))
{
//Do a jig.
}
});
Run Code Online (Sandbox Code Playgroud)
要开始观察,只需将节点定义为第一个参数和一个包含条件的对象:
observer.observe(tag_('body')[0], {childList: true});
Run Code Online (Sandbox Code Playgroud)
在这里做一些快速研究是第二个参数的对象的详尽示例:
{
attributes: false,
attributeOldValue: false,
//attributeFilter: array,
characterDataOldValue: false,
childList: true,
characterData: false,
subtree: false,
}
Run Code Online (Sandbox Code Playgroud)