是否有JavaScript/jQuery DOM更改侦听器? [英] Is there a JavaScript / jQuery DOM change listener?
问题描述
基本上,我想在DIV
的内容更改时执行脚本.由于这些脚本是分开的(Chrome扩展程序和网页脚本中的内容脚本),因此我需要一种方法来简单地观察DOM状态的变化.我可以设置轮询,但这似乎草率.
Essentially I want to have a script execute when the contents of a DIV
change. Since the scripts are separate (content script in the Chrome extension & webpage script), I need a way simply observe changes in DOM state. I could set up polling but that seems sloppy.
推荐答案
几年后,现在正式有了更好的解决方案. DOM4突变观察者替代了不推荐使用的DOM3突变事件.它们当前在现代浏览器中实现作为MutationObserver
(或作为供应商前缀的WebKitMutationObserver
Chrome的旧版本):
Several years later, there is now officially a better solution. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver
(or as the vendor-prefixed WebKitMutationObserver
in old versions of Chrome):
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更改,并将在元素属性更改和结构更改时触发.规范草案包含有效的变异侦听器属性的完整列表:
This example listens for DOM changes on document
and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:
childList
- 如果要观察到目标儿童的突变,请设置为
true
.
- Set to
true
if mutations to target's children are to be observed.
属性
- 如果要观察到目标属性的变异,请设置为
true
.
- Set to
true
if mutations to target's attributes are to be observed.
characterData
- 如果要观察到目标数据的变异,请设置为
true
.
- Set to
true
if mutations to target's data are to be observed.
子树
- 如果不仅要观察目标,还要观察目标的后代,请设置为
true
.
- Set to
true
if mutations to not just target, but also target's descendants are to be observed.
attributeOldValue
- 如果
attributes
设置为true并且需要记录突变之前目标的属性值,则设置为true
.
- Set to
true
ifattributes
is set to true and target's attribute value before the mutation needs to be recorded.
characterDataOldValue
- 如果
characterData
设置为true并且需要记录突变之前目标的数据,则设置为true
.
- Set to
true
ifcharacterData
is set to true and target's data before the mutation needs to be recorded.
attributeFilter
- 设置为属性本地名称(没有名称空间)的列表,如果不需要观察所有的属性突变.
(此列表为2014年4月的最新信息;您可以检查规格中是否有任何更改.)
(This list is current as of April 2014; you may check the specification for any changes.)
这篇关于是否有JavaScript/jQuery DOM更改侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!