[英]Adding Events for all the child nodes
Why is that adding an event to the document.querySelector('li')
works fine but Adding an event to the document.getElementsByTagName('li').childNodes
Results in error and how to overcome this problem and attach events to all Its child nodes successfully, I know using childNodes
creates an array but how do we add it. 为什么将事件添加到
document.querySelector('li')
可以正常工作,但将事件添加到document.getElementsByTagName('li').childNodes
为什么会导致错误,以及如何解决此问题并将事件附加到其所有子项节点成功,我知道使用childNodes
会创建一个数组,但是我们如何添加它。 Should I use a for
loop ? 我应该使用
for
循环吗?
You can add an event to an element but not to a collection. 您可以将事件添加到元素,但不能添加到集合。
You can access childNodes
from an element but not a collection. 您可以从元素而非集合中访问
childNodes
。 Note that childNodes
may include text nodes, which don't support event handlers. 请注意,
childNodes
可能包括不支持事件处理程序的文本节点。
What you want is document.querySelectorAll()
, which creates a collection of elements based on a CSS selector . 您需要的是
document.querySelectorAll()
,它基于CSS选择器创建元素的集合。
You can iterate through the collection using a for
loop, adding event listeners along the way: 您可以使用
for
循环遍历集合,并在此过程中添加事件侦听器:
var nodes= document.querySelectorAll('li > *'); for(var i = 0 ; i < nodes.length ; i++) { nodes[i].addEventListener('click', function() { alert('You clicked ' + this.textContent); }); }
li * {background: orange;}
<ul> <li>Lorem <em>ipsum</em> dolor <strong>sit</strong> amet</li> <li>Consectetur <em>adipiscing</em> elit</li> <li>beatae <em>vitae</em> dicta <strong>sunt</strong></li> </ul>
for(var element : document.getElementsByTagName('li')) {
Event.observe(element, "click", function(){...});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.