在 div 更改时触发 jQuery 事件
我有一个 div,它的内容可能会以各种方式发生变化:例如,它的整个内容可以通过 innerHTML 重新加载,或者可以通过 DOM 方法添加节点.这反过来可能通过原生 Javascript 或通过调用 jQuery API 或通过其他库间接发生.
I have a div whose content may change in various ways: for instance its whole content may be reloaded via innerHTML, or nodes may be added via DOM methods. This in turn may happen via native Javascript or indirectly via calls the jQuery API or via other libraries.
我想在 div 的内容发生变化时执行一些代码,但我完全无法控制 如何改变它.事实上,我正在设计一个可供其他人使用的小部件,他们可以按照自己喜欢的方式自由更改 div 的内容.当这个 div 的内部内容发生变化时,小部件的形状可能也必须更新.
I want to execute some code when the content of the div changes, but I have absolutely no control on how it will change. Indeed I am designing a widget that may be used by other people, who are free to change the content of their divs the way they prefer. When the inner content of this div changes, the shape of the widget may have to be updated as well.
我正在使用 jQuery.有没有办法捕捉到这个 div 的内容发生了变化的事件?
I'm using jQuery. Is there a way to capture the event that the content of this div has changed, however it happened?
推荐答案
您可以使用 DOMNodeInserted
和 DOMNodeRemoved
来检查是否添加或删除了元素.不幸的是,IE 不支持这个.
You can use DOMNodeInserted
and DOMNodeRemoved
to check if elements are added or removed. Unfortunately, IE doesn't support this.
$('#myDiv').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
if (event.type == 'DOMNodeInserted') {
alert('Content added! Current content:' + '
' + this.innerHTML);
} else {
alert('Content removed! Current content:' + '
' + this.innerHTML);
}
});
<小时>
更新
您可以使用 .data()
保存初始内容和未来的更改.这是一个例子.
Update
You could save the initial contents and future changes with .data()
. Here's an example.
var div_eTypes = [],
div_changes = [];
$(function() {
$('#myDiv').each(function() {
this['data-initialContents'] = this.innerHTML;
}).bind('DOMNodeInserted DOMNodeRemoved', function(event) {
div_eTypes.concat(e.type.match(/insert|remove/));
div_changes.concat(this.innerHTML);
});
});
示例输出:
> $('#myDiv').data('initialContents');
"<h1>Hello, world!</h1><p>This is an example.</p>"
> div_eTypes;
["insert", "insert", "remove"]
> div_changes;
["<iframe src='http://example.com'></iframe>", "<h4>IANA — Example domains</h4><iframe src='http://example.com'></iframe>", "<h4>IANA – Example domains</h4>"]
<小时>
更新 2
您可能还想包含 DOMSubtreeModified
,因为我发现 DOMNodeInserted
和 DOMNodeRemoved
不会触发元素innerHTML
被直接替换.在IE下还是不行,但至少在其他浏览器下可以正常使用.
Update 2
You may want to include DOMSubtreeModified
as well, because I've found out that DOMNodeInserted
and DOMNodeRemoved
don't trigger if an element's innerHTML
is replaced directly. It still doesn't work in IE, but at least it works fine in other browsers.
相关文章