问题
I have a page, on the left there is a list of links users can click, when they are clicked, a div on the right side will load the correct content via Ajax according to the link.
Now I want to fire a function when the right side div's content changed every time.
After a search in SO, I learn that there are Mutation Events, I use the DOMSubtreeModified
event:
right_div.addEventListener("DOMSubtreeModified", handler, false);
However, when I click the link on the left side, it seems that handler
will be called several time. I want it be called only once when the new contents of it has been loaded. How could I do this?
回答1:
The DOMSubtreeModified is "a general event for notification of all changes to the document". You can set mutation events for specific mutations:
- DOMAttrModified event
- DOMCharacterDataModified event
- DOMNodeInserted event
- DOMNodeInsertedIntoDocument event
- DOMNodeRemoved event
- DOMNodeRemovedFromDocument event
And there are the following types:
- DOMElementNameChanged
- DOMAttributeNameChanged
So if you are replacing a node, it might cause two (or more) mutation events - one when the node is removed, another when it is replaced. Futher events may also be dispatched, such as character data modified. if you are listening for an event only when the text content is changed, try the DOMCharacterDataModified event:
A user agent must dispatch this event after
CharacterData.data
orProcessingInstruction.data
have been modified, but the node itself has not been inserted or deleted. The proximal event target of this event must be theCharacterData
node or theProcessingInstruction
node.
来源:https://stackoverflow.com/questions/6210159/call-a-function-when-the-content-inside-a-div-is-changed