在DOM属性更改上触发事件

ts.*_*ts. 62 javascript jquery events dom dom-events

是否有任何方法可以触发属性更改事件(可能是自定义)?

让我们说,当IMG src被改变或DIV的innerHtml?

小智 51

注意:截至2012年,Mutation Events已从标准中删除,现已弃用.有关如何使用其替代品,请参阅其他答案或文档MutationObserver.

您指的是DOM Mutation Events.这些事件的浏览器支持很差(但正在改进).jQuery的Mutation Events插件可能会让你有所帮助.

  • 这些现已弃用,以支持`MutationObserver`,https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver (11认同)
  • 实际上,DOM突变事件在浏览器中得到了相当好的支持.这只是IE根本不支持它们(尽管IE 9会). (6认同)
  • @TimDown如果涉及到IE,它并不奇怪. (4认同)

Mat*_*ats 40

如何设置MutationObserver,主要是从MDN复制的,但为了清楚起见,我添加了自己的注释.

window.MutationObserver = window.MutationObserver
    || window.WebKitMutationObserver
    || window.MozMutationObserver;
// Find the element that you want to "watch"
var target = document.querySelector('img'),
// create an observer instance
observer = new MutationObserver(function(mutation) {
     /** this is the callback where you
         do what you need to do.
         The argument is an array of MutationRecords where the affected attribute is
         named "attributeName". There is a few other properties in a record
         but I'll let you work it out yourself.
      **/
}),
// configuration of the observer:
config = {
    attributes: true // this is to watch for attribute changes.
};
// pass in the element you wanna watch as well as the options
observer.observe(target, config);
// later, you can stop observing
// observer.disconnect();
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


Dav*_*ang 5

如果您只需要特定的东西,那么setInterval()通过每隔几毫秒检查一次目标属性就可以使用简单的东西:

var imgSrc = null;
setInterval(function () {
   var newImgSrc = $("#myImg").attr("src");
   if (newImgSrc !== imgSrc) {
      imgSrc = newImgSrc;
      $("#myImg").trigger("srcChange");
   }
}, 50);
Run Code Online (Sandbox Code Playgroud)

然后绑定到自定义"srcChange"事件:

$("#myImg").bind("srcChange", function () {....});
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,这段时间的使用真的很差(是的,这是'一种'方式). (23认同)