onchange 设计用于<select> 之类的输入 - 所以在这种情况下不会工作。您可以使用特定的与 dom 相关的事件(例如 DOMSubtreeModified),但这些事件不是跨浏览器并且具有不同的实现(它们甚至现在可能已被弃用) :
http://en.wikipedia.org/wiki/DOM_events
上面提到的MutationEvents 似乎已被MutationObservers 取代,我自己还没有使用过......但听起来它可以满足您的需求:
http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#mutation-observers
设置间隔
除此之外,您可以回退到 setInterval 处理程序,该处理程序将侦听目标元素中 HTML 的任何更改...当它发生更改时,您会触发一个函数。
function watch( targetElement, triggerFunction ){
/// store the original html to compare with later
var html = targetElement.innerHTML;
/// start our constant checking function
setInterval(function(){
/// compare the previous html with the current
if ( html != targetElement.innerHTML ) {
/// trigger our function when a change occurs
triggerFunction();
/// update html so that this doesn't keep triggering
html = targetElement.innerHTML;
}
},500);
}
function whenChangeHappens(){
alert('this will trigger when the html changes in my_target');
}
watch( document.getElementById('my_target'), whenChangeHappens );
jQuery 插件
如果你想把上面的内容用 jQuery 化成你可以应用到任何元素上的东西,它很容易修改:
/// set up the very simple jQuery plugin
(function($){
$.fn.domChange = function( whenChanged ){
/// we want to store our setInterval statically so that we
/// only use one for all the listeners we might create in a page
var _static = $.fn.domChange;
_static.calls = [];
_static.iid = setInterval( function(){
var i = _static.calls.length;
while ( i-- ) {
if ( _static.calls[i] ) {
_static.calls[i]();
}
}
}, 500 );
/// step each element in the jQuery collection and apply a
/// logic block that checks for the change in html
this.each (function(){
var target = $(this), html = target.html();
/// by adding the function to a list we can easily switch
/// in extra checks to the main setInterval function
_static.calls.push (function(){
if ( html != target.html() ) {
html = target.html();
whenChanged();
}
});
});
}
})(typeof jQuery != undefined && jQuery);
/// example code to test this
(function($){
$(function(){
$('div').domChange( function(){
alert('I was changed!');
} );
});
})(typeof jQuery != undefined && jQuery);
显然上面是一个非常简单的版本,应该扩展它来处理监听器的添加和删除。