简体   繁体   English

聆听诸如在JavaScript中添加新元素等事件

[英]Listening to events such as adding new elements in JavaScript

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? 任何想法如何使用?

.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/ js小提琴演示http//jsfiddle.net/PgAJT/

click here for example ... http://help.dottoro.com/ljmcxjla.php 点击这里例如 ... http://help.dottoro.com/ljmcxjla.php

Mutation events are deprecated, use Mutation Observer instead. 不推荐使用Mutation事件,而是使用Mutation Observer 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. 你也可以使用arri.js库,它在内部使用Mutation Observer并提供一个很好的简单api来监听元素的创建和删除。

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

DOMNodeInserted is deprecated in DOM Level 3 recommendation. 在DOM Level 3推荐中不推荐使用DOMNodeInserted。 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. 根据您的需要,在插入元素的代码中触发自定义事件可能是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM