问题描述
我需要收听< select>
的更改事件,但这只适用于第一个选择,有一个按钮可以添加更多< select>
到文档
,所以我需要检查是否有< select>
已更改,我正在执行以下操作:
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:
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);
但这仅在 DOMContentLoaded
时执行,如果我在 document.addEventListener
之外执行它不会执行。
but this only executes when DOMContentLoaded
and if I execute it outside the document.addEventListener
it doesn't executes.
PS我用纯JS做这个原因和 jQuery
一样,我用纯JS控制我的脚本。
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.
推荐答案
将事件直接附加到DOM节点很好,因为这些节点已经存在于DOM中。
Attaching events directly to DOM nodes is fine, given that those nodes already exist in the 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.
您可以使用事件冒泡:连接到节点的事件将被触发,用于节点本身及其所有父节点。在这里,我使用body元素作为父节点,但是你可以在任何元素上设置监听器,因为它是当前和未来选择元素的父元素:
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:
document.body.addEventListener("change", function(e) {
console.log(e.target);
}
查看此示例以获得更好的主意:。
Check out this example to get a better idea: http://jsfiddle.net/6HqqA/.
以下是对事件冒泡概念的一个很好的解释:。
Here's a good explanation of the concept of event bubbling: http://davidwalsh.name/event-delegate.
这篇关于在DOM Content Loaded之后附加的元素中的事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!