为ul下的li添加侦听事件
In JavaScript you add an event listener to a single element using this syntax:
在JavaScript中,您可以使用以下语法将事件侦听器添加到单个元素:
document.querySelector('.my-element').addEventListener('click', event => {
//handle click
})
But how can you attach the same event to multiple elements?
但是如何将同一事件附加到多个元素?
In other words, how to call addEventListener()
on multiple elements at the same time?
换句话说,如何在多个元素上同时调用addEventListener()
?
You can do this in 2 ways. One is using a loop, the other is using event bubbling.
您可以通过2种方式进行操作。 一种是使用循环 ,另一种是使用事件冒泡 。
使用循环 (Using a loop)
The loop is the simplest one conceptually.
从概念上讲,循环是最简单的循环。
You can call querySelectorAll()
on all elements with a specific class, then use forEach()
to iterate on them:
您可以对具有特定类的所有元素调用querySelectorAll()
,然后使用forEach()
对其进行迭代:
document.querySelectorAll('.some-class').forEach(item => {
item.addEventListener('click', event => {
//handle click
})
})
If you don’t have a common class for your elements you can build an array on the fly:
如果您的元素没有通用的类,则可以动态构建一个数组:
[document.querySelector('.a-class'), document.querySelector('.another-class')].forEach(item => {
item.addEventListener('click', event => {
//handle click
})
})
使用事件冒泡 (Using event bubbling)
Another option is to rely on event bubbling and attach the event listener on the body
element.
另一种选择是依赖事件冒泡 ,并将事件侦听器附加到body
元素上。
The event is always managed by the most specific element, so you can immediately check if that’s one of the elements that should handle the event:
该事件始终由最特定的元素管理,因此您可以立即检查该元素是否应该处理该事件:
const element1 = document.querySelector('.a-class')
const element2 = document.querySelector('.another-class')
body.addEventListener('click', event => {
if (event.target !== element1 && event.target !== element2) {
return
}
//handle click
}
翻译自: https://flaviocopes.com/how-to-add-event-listener-multiple-elements-javascript/
为ul下的li添加侦听事件