jQuery 监视 domElement 的变化?
我有一个将 html 标记注入页脚 div 的 ajax 回调.
I have an ajax callback which injects html markup into a footer div.
我想不通的是如何创建一种方法来监视 div 的内容何时发生变化.将我试图创建的布局逻辑放在回调中不是一个选项,因为每个方法(回调和我的布局 div 处理程序)不应该知道另一个.
What I can't figure out is how to create a way to monitor the div for when it's contents change. Placing the layout logic I'm trying to create in the callback isn't an option as each method (callback and my layout div handler) shouldn't know about the other.
理想情况下,我希望看到类似于 $('#myDiv').ContentsChanged(function() {...})
或 $(' 的某种事件处理程序#myDiv').TriggerWhenContentExists(function() {...})
Ideally I'd like to see some kind of event handler akin to $('#myDiv').ContentsChanged(function() {...})
or $('#myDiv').TriggerWhenContentExists( function() {...})
我找到了一个名为 watch 的插件和该插件的改进版本,但两者都无法触发.我尝试观看"我能想到的一切(即通过 ajax 注入更改 div 的高度属性),但根本无法让他们做任何事情.
I found a plugin called watch and an improved version of that plugin but could never get either to trigger. I tried "watching" everything I could think of (i.e. height property of the div being changed via the ajax injection) but couldn't get them to do anything at all.
有什么想法/帮助吗?
推荐答案
我发现最有效的方法是绑定到 DOMSubtreeModified
事件.它适用于 jQuery 的 $.html()
和标准 JavaScript 的 innerHTML
属性.
The most effective way I've found is to bind to the DOMSubtreeModified
event. It works well with both jQuery's $.html()
and via standard JavaScript's innerHTML
property.
$('#content').bind('DOMSubtreeModified', function(e) {
if (e.target.innerHTML.length > 0) {
// Content change handler
}
});
http://jsfiddle.net/hnCxK/
当从 jQuery 的 $.html()
调用时,我发现该事件触发了两次:一次是清除现有内容,一次是设置它.快速的 .length
-检查将在简单的实现中起作用.
When called from jQuery's $.html()
, I found the event fires twice: once to clear existing contents and once to set it. A quick .length
-check will work in simple implementations.
还需要注意的是,当设置为 HTML 字符串(即 '<p>Hello, world</p>'
)时,该事件将始终触发.并且该事件只会在更改时触发纯文本字符串.
It's also important to note that the event will always fire when set to an HTML string (ie '<p>Hello, world</p>'
). And that the event will only fire when changed for plain-text strings.
相关文章