数组元素上的简洁事件监听器 [英] Concise event listeners on array elements

查看:134
本文介绍了数组元素上的简洁事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更简洁的方法来执行相同的操作。

I was wondering if there is a more concise way to perform this same action.

我正在尝试监听两个执行相同操作的按钮上的事件动作,并且两个按钮都具有相同的返回类,我已将它们分配给名为 returnButton的数组。我想有一个事件侦听器,它可以侦听两个按钮,并将单击的按钮传递到我的returnToMainContent函数上。

I'm trying to listen for events on two separate buttons that perform the same action, and both buttons have the same class of 'return' and I've assigned them to an array called 'returnButton'. I'd like to have one event listener that can listen on both buttons and pass the button that was clicked onto my returnToMainContent function.

当前状态下的代码可以正常运行,但我认为应该有一种方法可以消除我的事件监听器之一。

The code in its current state functions properly, but I believe there should be a way to eliminate one of my event listeners. I'm floundering in my attempts to do so.

const returnButton = document.querySelectorAll('.return');
const mainContent = document.querySelector('#main-content');

returnButton[0].addEventListener('click', () => {returnToMainContent(returnButton[0])});
returnButton[1].addEventListener('click', () => {returnToMainContent(returnButton[1])});

function returnToMainContent(button){
    button.parentElement.style.display = "none";
    mainContent.style.display = "block";
}

非常感谢帮助!

推荐答案

如果只想对addEventListener进行一次调用,则可以通过在公共父元素上设置事件侦听器来使用事件委托。例如,您可以在 document 上进行设置。然后,您将从 <$ c来自事件对象的$ c> target 属性,该属性会自动传递给事件侦听器

If you just want to have a single call to addEventListener then you can use event delegation by setting the event listener on a common parent element. For instance you could set it on document. You would then get which button that was clicked from the target property from the event object that is automatically passed to event listeners

document.addEventListener('click',event=>{
  var button = event.target;
  //check that the element click was one of the 'return' buttons
  if(button.classList.contains('return')){
    returnToMainContent(button);
  }
});

function returnToMainContent(button){
    button.parentElement.style.display = "none";
    mainContent.style.display = "block";
}

这篇关于数组元素上的简洁事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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