javascript - Javascript:MutationObserver 不显示更改的节点
问题描述
这MutationObserver
是一个简单的 API,允许我监控 DOM 更改。我在 chrome 扩展中使用它,我想知道何时添加网页上的某些元素。并使用childList
应该告诉我指定目标何时添加新节点的选项。
来自 Mozilla 文档:https ://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit/childList
通过将 childList 设置为 true,只要将节点添加到 DOM 节点或从被监视的节点中删除,就会调用您的回调。
但在回调中change.addedNodes
andchange.removedNodes
是假的。即使打印目标”childNodes.length
表明孩子的数量实际上在变化
let content_box = document.querySelector('div#content-box'); // target to monitor
// create observer with callback
let observer = new MutationObserver( (mutations, observer) => {
mutations.forEach( change => {
console.log(`Added: ${change.addedNodes==true}`) // no added nodes (there should be)
console.log(`Removed ${change.removedNodes==true}`) // no removed nodes (which is fine)
console.log(change.target) // I've confirmed the target is the correct one
console.log(change.target.childNodes.length) // after multiple callbacks the length of children is actually increasing
})
})
observer.observe(content_box, {
childList: true, // monitoring for childList changes
attributes: false,
subtree: false,
})
解决方案
您想检查该属性addedNodes
是否在change
. 所以console.log("addedNodes" in change)
要得到一个真实的结果。
let content_box = document.querySelector('div#content-box'); // target to monitor
// create observer with callback
let observer = new MutationObserver( (mutations, observer) => {
mutations.forEach( change => {
console.log(`Added: ${"addedNodes" in change}`) // no added nodes (there should be)
console.log(`Removed ${"removedNodes" in change}`) // no removed nodes (which is fine)
console.log(change.target) // I've confirmed the target is the correct one
console.log(change.target.childNodes.length) // after multiple callbacks the length of children is actually increasing
})
})
observer.observe(content_box, {
childList: true, // monitoring for childList changes
attributes: false,
subtree: false,
})
推荐阅读
- laravel - Laravel 数据透视表关系数据未检索
- javascript - 为什么我的网站加载带有旧内容的 js 文件?
- java - LDAP 上的登录用户获取所有详细信息
- angular - 角度输入类型 datetime-local
- python - 如何遍历两组 json 键值对
- windows - 批处理脚本打印增量数字
- jenkins - 构建完成后,我们可以将 Jenkins 作业中存在的 Python 脚本的输出作为邮件发送吗?
- database - 如果 MongoDB 中的字符串太长,我应该将唯一字符串存储到 _id 中吗?
- java - 如何使用片段中的数据更改导航标题中的用户名?
- gerrit - 如何获取经过自我审查的 Gerrit 更改列表