Listening to events such as adding new elements in JavaScript

我的梦境 提交于 2019-12-18 12:47:38

问题


I need to create an event listener such that, when a new element is added to the document, or any of its child, my event handler gets called.

Any ideas how to do this using?


回答1:


.bind('DOMNodeInserted DOMNodeRemoved')

this are the events to check element is inserted or removed.

bind on parent element this event.

and call your function in handler

js fiddle demo : http://jsfiddle.net/PgAJT/

click here for example... http://help.dottoro.com/ljmcxjla.php




回答2:


Mutation events are deprecated, use Mutation Observer instead. You can also use arrive.js library, it uses Mutation Observer internally and provides a nice simple api to listen for elements creation and removal.

$('#container').arrive('.mySelector', function(){
    var $newElem = $(this);
});



回答3:


DOMNodeInserted is deprecated in DOM Level 3 recommendation. using them slows browsers down (they say). depending on what you need it for, it might make sense to trigger a custom event inside the code where you insert the element.



来源:https://stackoverflow.com/questions/9666914/listening-to-events-such-as-adding-new-elements-in-javascript

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