jQuery 观察 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3233991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery watch div
提问by atp
Is there any way to watch, if the content within a div changes?
如果 div 中的内容发生变化,有什么方法可以观看吗?
Let's say I have:
假设我有:
<div id="hello"><p>Some content here</p></div>
Which at some point 5 seconds later changes to:
在 5 秒后的某个时刻更改为:
<div id="hello"><ul><li>This is totally different!</li></ul></div>
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.
我如何通过回调或其他方式收到通知?在大多数情况下,我可以得到正在进行插入的 javascript,告诉我。但我想知道这是否可能。
回答by Sebastián Grignoli
The jQuery .change() method works only for form fields.
jQuery .change() 方法仅适用于表单字段。
I wrote a little jQuery plugin for you:
我为你写了一个小 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>
Be aware that this watches changes in the contents of the element (html) only, not the attributes.
请注意,这仅监视元素 (html) 内容的更改,而不是属性。
回答by gnarf
There is no native jQuery/DOM event that will fire when HTML/DOM content changes.
没有原生 jQuery/DOM 事件会在 HTML/DOM 内容更改时触发。
You could (if you are feeling particularly wasteful) do something like this:
你可以(如果你觉得特别浪费)做这样的事情:
$(function() {
var $div = $("#hello");
var html = $div.html();
var checking = setInterval(function() {
var newhtml = $div.html();
if (html != newhtml) {
myCallback();
html = newhtml;
}
},100);
function myCallback() {
alert('content changed!');
// if you only want it to fire once, uncomment the following:
// clearInterval(checking);
}
});
Just remember, calling .html()
every 100ms is probably not the best idea for your sites performance.
请记住,.html()
每 100 毫秒调用一次可能不是您网站性能的最佳选择。
回答by Nixter
Maybe, it's reasonable to monitor the source of events that amend the contents of your layer(s)? Say, a user has clicked anywhere (read, "did a click") after what the contents may had changed. So if you check the .html() after a click rather than using a loop - it might save some system resources.
也许,监视修改图层内容的事件源是否合理?假设,用户在内容可能发生变化后点击了任何地方(阅读,“点击”)。因此,如果您在单击后检查 .html() 而不是使用循环 - 它可能会节省一些系统资源。
回答by psychotik
Who/what will change this? If it's some JS you control, use that to also trigger your callback. Obviously a user cannot change this.
谁/什么会改变这一点?如果是您控制的某些 JS,请使用它来触发您的回调。显然,用户不能改变这一点。
If you want to watch a <input>
element etc, use the 'change' event. jQuery version here: http://api.jquery.com/change/
如果您想观看<input>
元素等,请使用 'change' 事件。jQuery 版本在这里:http: //api.jquery.com/change/
回答by a7drew
Here's a code sample that calls a simple alert when the given value changes:
这是一个代码示例,它在给定值更改时调用一个简单的警报:
<!DOCTYPE html>
<html lang="en">
<head>
<title>watchu, watchu, watchu want, watchu want?</title>
</head>
<body>
<div id='foo'>Hello World!</div>
<p><input type="button" id="ChangeButton" value="Change It" /></p>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function () {
$('#ChangeButton').click(function () {
$('#foo').html('Awfveeterzain!');
});
window.watchForChangeOriginalValue = $('#foo').html();
watchForChange();
});
function watchForChange() {
if ($('#foo').html() != window.watchForChangeOriginalValue)
alert('the value changed!');
else
window.setTimeout(watchForChange, 500);
}
</script>
</body>
</html>
回答by Prem
There are some events called DOMNodeInserted
, DOMNodeRemoved
and DOMSubtreeModified
. Which check is there any elements are added or removed or any inner Html changed inside a div. for this you need an setInterval()
function.
有一些事件称为DOMNodeInserted
,DOMNodeRemoved
和DOMSubtreeModified
。哪个检查是否添加或删除了任何元素或在 div 内更改了任何内部 Html。为此,您需要一个setInterval()
功能。
function DivChange() {
$('#YourDiv').bind('DOMNodeInserted DOMNodeRemoved', function (event) {
if (event.type == 'DOMNodeInserted') {
alert('Content added');
} else if (event.type == 'DOMNodeRemoved') {
alert('Content removed');
} else {
alert('Inner Html changed for some content');
}
});
}
var DivTimer = setInterval(DivChange, 1000);
The above functions will checks the Div for any content change, for every second
上述函数将每秒检查 Div 是否有任何内容更改
Note: This events are not supported by IE
注意:IE 不支持此事件