我已经实现了一个突变观察器,可以监视页面加载的突变。我特意寻找加载/存在特定元素的点。我可以通过它的类名来指定它,例如foo
。
当在变异对象列表中找到foo
时,我希望调用一个函数。
目前,我有以下内容:
mutations.forEach(mutation => {
if (!mutation.addedNodes || mutation.addedNodes[0].className === undefined || mutation.addedNodes[0].className !== 'foo') {
return;
} else {
console.log(mutation.addedNodes[0].className + ' loaded!');
}
});
这在技术上有效:当它通过三个条件时,我确实看到了控制台日志。
但是,如果mutation.addedNodes[0]
没有任何className
数据,则会提供错误
无法读取属性' className'未定义的
我明白为什么会这样;有时mutations
没有addedNodes[0]
所以确实是未定义的。我不确定的是只有当上述测试通过时,才能触发控制台日志(以后将是我的函数)的最佳方法。
我还在学习ES6,我希望有一些东西可以帮助我,但我只是在努力寻找最好的方法。
答案 0 :(得分:1)
addedNodes
并检查每个树。addedNodes
将是一个空数组。
const matching = [];
for (const {addedNodes} of mutations) {
for (const node of addedNodes) {
if (node.nodeType !== Node.ELEMENT_NODE) {
continue;
}
if (node.classList.contains(className)) {
matching.push(node);
}
if (node.children[0]) {
matching.push(...node.getElementsByClassName(className));
}
}
}
if (matching.length) console.log(matching);