javascript DOM 内容加载后追加的元素中的事件侦听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16512016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Event listener in elements appended after DOM Content Loaded
提问by Memolition
I need to listen a "change" event of a <select>
but this works fine only on the first select, there's a button that adds more <select>
to the document
, so I need to check if any <select>
is changed, I'm doing something like this:
我要听的是“改变”事件<select>
,但能正常工作只在第一次选择,有这么多添加一个按钮<select>
的document
,所以我需要检查是否有任何<select>
改变,我做这样的事情:
document.addEventListener('DOMContentLoaded', function() {
var selects = document.getElementsByClassName('select');
for(var i=0;i < selects.length;i++) {
selects[0].addEventListener('change', function() {
// do something here...
}, false);
}
}, flase);
but this only executes when DOMContentLoaded
and if I execute it outside the document.addEventListener
it doesn't executes.
但这仅在当DOMContentLoaded
我在外部执行时执行,document.addEventListener
它不会执行。
P.S. I'm doing this with pure JS cause is the same with jQuery
and I've more control over my script with pure JS.
PS我用纯JS做这件事的原因是一样的jQuery
,我可以用纯JS更好地控制我的脚本。
回答by sixFingers
Attaching events directly to DOM nodes is fine, given that those nodes already exist in the DOM.
将事件直接附加到 DOM 节点是可以的,因为这些节点已经存在于 DOM 中。
But, as your case requests, there's a better approach that allows to bind handlers for given events to current nodes AND nodes added in the future.
但是,根据您的情况要求,有一种更好的方法可以将给定事件的处理程序绑定到当前节点和将来添加的节点。
You can make use of event bubbling: events attached to a node get triggered for the node itself and all of its parents. Here, i make use of body element as the parent node, but you can set the listener on any element given it is parent to current and future select elements:
您可以使用事件冒泡:附加到节点的事件会为节点本身及其所有父节点触发。在这里,我使用 body 元素作为父节点,但是您可以在任何元素上设置侦听器,因为它是当前和未来选择元素的父元素:
document.body.addEventListener("change", function(e) {
console.log(e.target);
}
Check out this example to get a better idea: http://jsfiddle.net/6HqqA/.
查看此示例以获得更好的主意:http: //jsfiddle.net/6HqqA/。
Here's a good explanation of the concept of event bubbling: http://davidwalsh.name/event-delegate.
这是事件冒泡概念的一个很好的解释:http: //davidwalsh.name/event-delegate。
回答by sergioadh
Don't attach them that way, use the on function from jquery
不要以这种方式附加它们,使用 jquery 的 on 函数
$(document).on('change', 'select', function(){
// your code
});
回答by Mohammad Adil
Try this (with jquery) -
试试这个(使用 jquery) -
$(function(){
$(document).on('change','select', function(){
// do something here...
var val = $(this).val();
});
});
This will work even if you add multiple select's dynamically
即使您动态添加多个选择,这也将起作用