想要添加“ addEventListener”在同一个类的多个元素上 [英] Want to add "addEventListener" on multiple elements with same class

查看:656
本文介绍了想要添加“ addEventListener”在同一个类的多个元素上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过jS中的事件监听器在 onClick中执行逻辑,但似乎只运行一次?我在全部四个课程中都上过课,但是我不知道为什么它似乎只对第一个有效?

I'd like to perform the logic in the "onClick" through the event listener in jS but it only seems to run once? I have the class in all four but I can't figure out why it seems to only work for the first?

HTML:

<button id='btn-1' type="button" name="first" class="breakdown main-text" onclick="enableButton('btn-2');disableButton('btn-1');show('btn-1')"> Breakdown Start </button>
<button id='btn-2' type="button" name="second" class="breakdown main-text" onclick="enableButton('btn-3');disableButton('btn-2');show('btn-2')" disabled> Repair Start </button>
<button id='btn-3' type="button" name="third" class="breakdown main-text" onclick="enableButton('btn-4');disableButton('btn-3');show('btn-3')" disabled> Repair End </button>
<button id='btn-4' type="button" name="fourth" class="breakdown main-text" onclick="show('btn-4')" disabled> Breakdown Ended </button>

JS:

let button1 = document.querySelector('#btn-1')
let button2 = document.querySelector('#btn-2');
let button3 = document.querySelector('#btn-3');
let button4 = document.querySelector('#btn-4');


const breakdownButton = document.querySelector('.breakdown');
breakdownButton.addEventListener('click', function() {
console.log(this.innerHTML);
});


推荐答案

您需要使用 querySelectorAll 会返回一个集合。现在使用 spread运算符(三个点)将其转换为数组,并使用 forEach 。在 forEach 回调中将事件侦听器添加到其中

You need to use querySelectorAll which will return a collection.Now use spread operator (three dots) to convert it to array and use forEach .Inside forEach callback add the event listener to it

[...document.querySelectorAll('.breakdown')].forEach(function(item) {
  item.addEventListener('click', function() {
    console.log(item.innerHTML);
  });
   });

<button id='btn-1' type="button" name="first" class="breakdown main-text"> Breakdown Start </button>
<button id='btn-2' type="button" name="second" class="breakdown main-text" disabled> Repair Start </button>
<button id='btn-3' type="button" name="third" class="breakdown main-text" disabled> Repair End </button>
<button id='btn-4' type="button" name="fourth" class="breakdown main-text" disabled> Breakdown Ended </button>

在您的代码段中,您还拥有

In your snippet you have also attached inline event handler,that may not be necessary.

如果目标是启用下一个按钮,则使用函数可以从事件处理程序的回调函数中调用它

If the objective is to enable the next button then a function to enable it can be called from the callback function of the event handler

这篇关于想要添加“ addEventListener”在同一个类的多个元素上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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