Vanilla JS的事件委托 [英] Event delegation with vanilla JS

查看:49
本文介绍了Vanilla JS的事件委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于以下HTML标记:

Based on the following HTML markup:

<div class='list-container'>
  <button class="btn">More details </button>
</div>

<div class="details">Lorem ipsum lorem ipsum lorem ipsum</div>

我编写了以下JavaScript代码:

I wrote the following JavaScript code:

let btn = document.querySelector('.btn');
let detailsContainer = document.querySelector('.details');

btn.addEventListener('click', function(e) {
  e.preventDefault();
  detailsContainer.classList.toggle('visible');
});

但是我需要更改JS代码以使用事件委托,以便将eventListener添加到 list-container 而不是btn中.

But I need to change the JS code to use the event delegation so that the eventListener gets added to the list-container instead of to the btn.

在jQuery中很容易,但是如何在香草JS中做到呢?

It's easy in jQuery, but how can I do it in vanilla JS?

推荐答案

只需将侦听器添加到 .list-container ,然后单击以查看 target 匹配 .btn :

Just add a listener to the .list-container instead, and on click, check to see if the target matches the .btn:

const detailsContainer = document.querySelector('.details');
document.querySelector('.list-container').addEventListener('click', ({ target }) => {
  if (target.matches('.btn')) detailsContainer.classList.toggle('visible');
});

.details { display: none }
.visible { display: block }

<div class='list-container'>container outside of button
  <button class="btn">More details </button>
</div>

<div class="details">Lorem ipsum lorem ipsum lorem ipsum</div>

这篇关于Vanilla JS的事件委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆