問(wèn)題描述
我有一個(gè)將 html 標(biāo)記注入頁(yè)腳 div 的 ajax 回調(diào).
I have an ajax callback which injects html markup into a footer div.
我想不通的是如何創(chuàng)建一種方法來(lái)監(jiān)視 div 的內(nèi)容何時(shí)發(fā)生變化.將我試圖創(chuàng)建的布局邏輯放在回調(diào)中不是一個(gè)選項(xiàng),因?yàn)槊總€(gè)方法(回調(diào)和我的布局 div 處理程序)不應(yīng)該知道另一個(gè).
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() {...})
我找到了一個(gè)名為 watch 的插件和該插件的改進(jìn)版本,但兩者都無(wú)法觸發(fā).我嘗試觀看"我能想到的一切(即通過(guò) ajax 注入更改 div 的高度屬性),但根本無(wú)法讓他們做任何事情.
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.
有什么想法/幫助嗎?
推薦答案
我發(fā)現(xiàn)最有效的方法是綁定到 DOMSubtreeModified
事件.它適用于 jQuery 的 $.html()
和標(biāo)準(zhǔn) 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/
當(dāng)從 jQuery 的 $.html()
調(diào)用時(shí),我發(fā)現(xiàn)該事件觸發(fā)了兩次:一次是清除現(xiàn)有內(nèi)容,一次是設(shè)置它.快速的 .length
-檢查將在簡(jiǎn)單的實(shí)現(xiàn)中起作用.
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.
還需要注意的是,當(dāng)設(shè)置為 HTML 字符串(即 '<p>Hello, world</p>'
)時(shí),該事件將始終觸發(fā).并且該事件只會(huì)在更改時(shí)觸發(fā)純文本字符串.
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.
這篇關(guān)于jQuery 監(jiān)視 domElement 的變化?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!