jQuery watch div [英] jQuery watch div
本文介绍了jQuery watch div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果div中的内容发生变化,有什么办法可以观看?
Is there any way to watch, if the content within a div changes?
假设我有:
<div id="hello"><p>Some content here</p></div>
5秒后的某个时间更改为:
Which at some point 5 seconds later changes to:
<div id="hello"><ul><li>This is totally different!</li></ul></div>
如何通过回调或其他方式通知我?在大多数情况下,我可以得到正在执行插入操作的javascript.但是我想知道是否有可能.
How can I be notified of this via a callback or something else? I can in most cases get the javascript that's doing the inserting, to tell me. But I wanted to know if it was possible.
推荐答案
jQuery .change()方法仅适用于表单字段.
The jQuery .change() method works only for form fields.
我为您编写了一个jQuery插件:
I wrote a little jQuery plugin for you:
<!-- jQuery is required -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<!-- this is the plugin -->
<script>
jQuery.fn.contentChange = function(callback){
var elms = jQuery(this);
elms.each(
function(i){
var elm = jQuery(this);
elm.data("lastContents", elm.html());
window.watchContentChange = window.watchContentChange ? window.watchContentChange : [];
window.watchContentChange.push({"element": elm, "callback": callback});
}
)
return elms;
}
setInterval(function(){
if(window.watchContentChange){
for( i in window.watchContentChange){
if(window.watchContentChange[i].element.data("lastContents") != window.watchContentChange[i].element.html()){
window.watchContentChange[i].callback.apply(window.watchContentChange[i].element);
window.watchContentChange[i].element.data("lastContents", window.watchContentChange[i].element.html())
};
}
}
},500);
</script>
<!-- some divs to test it with -->
<p>Testing it: (click on divs to change contents)</p>
<div id="a" onclick="$(this).append('i')">Hi</div>
<div id="b" onclick="$(this).append('o')">Ho</div>
<div class="c" onclick="$(this).append('y')">He</div>
<div class="c" onclick="$(this).append('w')">He</div>
<div class="c" onclick="$(this).append('a')">He</div>
<!-- this is how to actually use it -->
<script>
function showChange(){
var element = $(this);
alert("it was '"+element.data("lastContents")+"' and now its '"+element.html()+"'");
}
$('#a').contentChange(function(){ alert("Hi!") });
$('div#b').contentChange( showChange );
$('.c').contentChange(function(){ alert("He he he...") });
</script>
请注意,这仅监视元素(html)内容的变化,而不是属性的变化.
Be aware that this watches changes in the contents of the element (html) only, not the attributes.
这篇关于jQuery watch div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文