本质上,我希望在 DIV
的内容发生更改时执行脚本。由于脚本是分开的(Chrome 扩展程序中的内容脚本和网页脚本),我需要一种简单观察 DOM 状态变化的方法。我可以设置投票,但这看起来很草率。
最佳答案
长期以来,DOM3 突变事件是最佳可用解决方案,但由于性能原因已被弃用。 DOM4 Mutation Observers是已弃用的 DOM3 突变事件的替代品。他们是currently implemented in modern browsers作为 MutationObserver
(或者在旧版本的 Chrome 中作为 vendor 前缀的 WebKitMutationObserver
):
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
console.log(mutations, observer);
// ...
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
attributes: true
//...
});
此示例监听 document
及其整个子树上的 DOM 更改,并且它将在元素属性的更改以及结构更改时触发。规范草案包含有效 mutation listener properties 的完整列表。 :
childList
- Set to
true
if mutations to target's children are to be observed.attributes
- Set to
true
if mutations to target's attributes are to be observed.characterData
- Set to
true
if mutations to target's data are to be observed.subtree
- Set to
true
if mutations to not just target, but also target's descendants are to be observed.attributeOldValue
- Set to
true
ifattributes
is set to true and target's attribute value before the mutation needs to be recorded.characterDataOldValue
- Set to
true
ifcharacterData
is set to true and target's data before the mutation needs to be recorded.attributeFilter
- Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.
(此列表截至 2014 年 4 月为最新;您可以检查规范是否有任何更改。)
关于javascript - 是否有 JavaScript/jQuery DOM 更改监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40042725/