javascript jQuery:如何检测给定元素中的 html 是否已更改?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4950199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: How can I detect if the html has changed within a given element?
提问by JohnIdol
In javascript, possibly using jQuery, how can I detect if the html content of a given element has changed?
在 javascript 中,可能使用 jQuery,如何检测给定元素的 html 内容是否已更改?
I'd like to be able to do somthing like:
我希望能够做类似的事情:
$('#myDiv').change(function(){
// do some stuff
});
I am basically trying to detect if given elements are being added to the div or if the inner html of given elements (such as labels) has changed and then hide or show the div depending on the content.
我基本上是在尝试检测给定元素是否被添加到 div 中,或者给定元素(例如标签)的内部 html 是否已更改,然后根据内容隐藏或显示 div。
Any alternative idea about how to achieve smt like this is also appreciated.
任何关于如何像这样实现 smt 的替代想法也受到赞赏。
I am hoping I won't have to revert to some obscure plugin to do this!
我希望我不必恢复到一些晦涩的插件来做到这一点!
NOTE: this needs to work at least in IE8!
注意:这至少需要在 IE8 中工作!
回答by jAndy
You can use the DOM Level 3 event DOMNodeInserted. Example:
您可以使用 DOM Level 3 事件DOMNodeInserted。例子:
$('#myDiv').bind('DOMNodeInserted', function(e) {
console.log('element: ', e.target, ' was inserted);
});
Demo: http://www.jsfiddle.net/vsgdZ/1/
演示:http: //www.jsfiddle.net/vsgdZ/1/
The event will fire whenever a new node was appended to the element on which you bind the handler.
每当将新节点附加到绑定处理程序的元素时,就会触发该事件。

