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.
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.
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