jQuery watch for domElement changes?(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.
这篇关于jQuery 监视 domElement 的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:jQuery 监视 domElement 的变化?
基础教程推荐
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01