问题描述
为什么将事件添加到 document.querySelector('li')
工作正常但
将事件添加到 document.getElementsByTagName('li')。childNodes
导致错误以及如何解决此问题并将事件附加到所有
其子节点成功,我知道使用 childNodes
创建一个数组,但我们如何添加它。我应该使用进行
循环吗?
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 allIts child nodes successfully, I know using childNodes
creates an array but how do we add it. Should I use a for
loop ?
推荐答案
您可以添加活动到元素但不到集合。
You can add an event to an element but not to a collection.
您可以从元素访问 childNodes
但不能从集合访问。请注意, childNodes
可能包含不支持事件处理程序的文本节点。
You can access childNodes
from an element but not a collection. Note that childNodes
may include text nodes, which don't support event handlers.
你想要的是什么 ,根据。
What you want is document.querySelectorAll()
, which creates a collection of elements based on a CSS selector.
您可以使用<$ c $遍历集合c> for 循环,沿途添加事件监听器:
You can iterate through the collection using a for
loop, adding event listeners along the way:
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>
这篇关于为所有子节点添加事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!