触发DOM属性更改事件

有没有办法触发事件(可能是自定义)的属性更改?

比方说,当IMG的src改变或DIV的innerHtml?

注意:截至2012年,突变事件已从标准中删除,现已被弃用。 请参阅其他答案或文档以了解如何使用替代品MutationObserver

您指的是DOM突变事件 。 浏览器对这些事件的支持很差(但有所改进)。 jQuery的突变事件插件可能会帮助你。

如何设置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(); 

希望这可以帮助。

如果你只需要一些特定的东西,那么一个简单的setInterval()就可以工作,每隔几毫秒检查一次目标属性:

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

然后绑定到自定义的“srcChange”事件:

 $("#myImg").bind("srcChange", function () {....}); 

没有本地dom更改事件,你可以挂钩到。

这里的好文章,试图提供一个jQuery插件的forms的解决scheme。

来自文章的代码

 $.fn.watch = function(props, callback, timeout){ if(!timeout) timeout = 10; return this.each(function(){ var el = $(this), func = function(){ __check.call(this, el) }, data = { props: props.split(","), func: callback, vals: [] }; $.each(data.props, function(i) { data.vals[i] = el.css(data.props[i]); }); el.data(data); if (typeof (this.onpropertychange) == "object"){ el.bind("propertychange", callback); } else if ($.browser.mozilla){ el.bind("DOMAttrModified", callback); } else { setInterval(func, timeout); } }); function __check(el) { var data = el.data(), changed = false, temp = ""; for(var i=0;i < data.props.length; i++) { temp = el.css(data.props[i]); if(data.vals[i] != temp){ data.vals[i] = temp; changed = true; break; } } if(changed && data.func) { data.func.call(el, data); } } }