Call a function when the content inside a div is changed?

女生的网名这么多〃 提交于 2019-12-25 06:47:11

问题


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:

  1. DOMAttrModified event
  2. DOMCharacterDataModified event
  3. DOMNodeInserted event
  4. DOMNodeInsertedIntoDocument event
  5. DOMNodeRemoved event
  6. DOMNodeRemovedFromDocument event

And there are the following types:

  1. DOMElementNameChanged
  2. 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 or ProcessingInstruction.data have been modified, but the node itself has not been inserted or deleted. The proximal event target of this event must be the CharacterData node or the ProcessingInstruction node.



来源:https://stackoverflow.com/questions/6210159/call-a-function-when-the-content-inside-a-div-is-changed

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