gpt4 book ai didi

jQuery watch div

转载 作者:行者123 更新时间:2023-12-03 21:31:39 25 4
gpt4 key购买 nike

如果 div 中的内容发生变化,有什么方法可以观察吗?

假设我有:

<div id="hello"><p>Some content here</p></div>

在 5 秒后的某个时刻更改为:

<div id="hello"><ul><li>This is totally different!</li></ul></div>

如何通过回调或其他方式通知我这一点?在大多数情况下,我可以得到正在执行插入操作的 JavaScript 来告诉我。但我想知道这是否可能。

最佳答案

jQuery .change() 方法仅适用于表单字段。

我为你写了一个小 jQuery 插件:

<!-- 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) 内容的更改,而不是属性的更改。

关于jQuery watch div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3233991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com