jQuery watch div

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

Is there any way to watch, if the content within a div changes?

Let's say I have:

Some content here

Which at some point 5 seconds later changes to:

  • This is totally different!

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.

回答1:

The jQuery .change() method works only for form fields.

I wrote a little jQuery plugin for you:

  

Testing it: (click on divs to change contents)

Hi
Ho
He
He
He

Be aware that this watches changes in the contents of the element (html) only, not the attributes.



回答2:

There is no native jQuery/DOM event that will fire when HTML/DOM content changes.

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.

jsFiddle mockup



回答3:

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.



回答4:

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.

If you want to watch a element etc, use the 'change' event. jQuery version here: http://api.jquery.com/change/



回答5:

Here's a code sample that calls a simple alert when the given value changes:

       watchu, watchu, watchu want, watchu want?
Hello World!



回答6:

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.

 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

Note: This events are not supported by IE



文章来源: jQuery watch div
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!