JavaScript一个EventListener统治所有人与多个听众(最佳实践)
您好,我一直在互联网上寻找,试图找出向我的网站添加事件监听器的最佳实践,通常有以下两种方法:
使用循环向每个元素(例如按钮)添加事件监听器:
document.querySelectorAll('.some-button').forEach(item => {
item.addEventListener('click', event => {
//handle click
})
})
或使用事件冒泡仅使用一个侦听器并检查每个场景的 e.target:
body.addEventListener('click', event => {
if (event.target !== element1 && event.target !== element2) {
//return
}
//handle click
}
但是,我无法找到任何比较这两种方法性能的文章。根据我有限的理解,每当有“点击”时,javascript都会循环遍历所有事件侦听器(即使您没有点击它),因此我采用第二种方法(使用一个事件侦听器),这似乎是成为更容易管理的人。
如果有人可以对第二种方法的潜在缺点以及是否会出现任何性能问题提供进一步的见解,谢谢。
Hi I have been looking on the internet trying to figure out the best practice for adding eventlistener to my websites and it generally comes down with two approaches as follow:
Adding an event listener to every elements (e.g. button) using a loop:
document.querySelectorAll('.some-button').forEach(item => {
item.addEventListener('click', event => {
//handle click
})
})
Or using event bubbling to use one listener only and check the e.target for each scenario:
body.addEventListener('click', event => {
if (event.target !== element1 && event.target !== element2) {
//return
}
//handle click
}
However, I was unable to find any article comparing the performance of these 2 approaches. From my limited understanding, whenever there is a 'click' javascript will loop through all the eventlisteners anyway (even though if you didn't click on it) and for that reason I am taking the second approach (using one eventlistener) which seems to be the easier one to manage.
Appreciate if someone can provide further insights on the potential drawback of the second approach and if there will be any performance issue thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论