是否有 JavaScript/jQuery DOM 更改侦听器? [英] Is there a JavaScript / jQuery DOM change listener?

查看:40
本文介绍了是否有 JavaScript/jQuery DOM 更改侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本质上,我希望在 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.

推荐答案

长期以来,DOM3 突变事件是最好的可用解决方案,但由于性能原因,它们已被弃用.DOM4 Mutation Observers 是已弃用的 DOM3 突变事件的替代品.它们目前在现代浏览器中实现作为MutationObserver(或作为供应商-在旧版 Chrome 中添加前缀 WebKitMutationObserver:

For a long time, DOM3 mutation events were the best available solution, but they have been deprecated for performance reasons. 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.

属性

  • 如果要观察到目标属性的突变,则设置为 true.

字符数据

  • 如果要观察到目标数据的突变,则设置为 true.

子树

  • 如果不仅要观察到目标的突变,还要观察目标的后代的突变,则设置为 true.

attributeOldValue

  • 如果attributes设置为true,并且需要记录突变前目标的属性值,则设置为true.
  • Set to true if attributes is set to true and target's attribute value before the mutation needs to be recorded.

characterDataOldValue

  • 如果characterData 设置为true 并且需要记录突变前的目标数据,则设置为true.
  • Set to true if characterData is set to true and target's data before the mutation needs to be recorded.

属性过滤器

  • 如果不需要观察所有属性突变,则设置为属性本地名称列表(不带命名空间).

(此列表截至 2014 年 4 月是最新的;您可以查看规范以了解任何更改.)

(This list is current as of April 2014; you may check the specification for any changes.)

这篇关于是否有 JavaScript/jQuery DOM 更改侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆