将事件侦听器绑定到具有相同类的多个元素 [英] Binding an event listener to multiple elements with the same class

查看:77
本文介绍了将事件侦听器绑定到具有相同类的多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将带有JavaScript的 onclick 事件应用于以下元素:

I'm trying to apply the onclick event with JavaScript to the following elements:

<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>

如果我点击第一个元素(带索引[0]),那么这可行,但是我是
需要此事件适用于所有类:

If I click on the first element (with index [0]) then this works, but I need this event applicable for all classes:

document.getElementsByClassName('abc')[0].onclick="function(){fun1();}";
function  fun1(){
document.getElementsByClassName('abc').style.color="red"; 
}


推荐答案

扩展所提供的解决方案通过@rock star,我在函数中添加了两个小的附加内容。首先,最好将一个类(带有关联的样式规则)添加/重新移动到元素,而不是直接将样式器应用于元素。

To expand on the solution provided by @rock star I added two small additions to the function. First it is better to add / reemove a class (with an associated style rule) to an element than directly applying the stylerule to the element.

其次 - 在click事件上 - 现在将从先前选择的元素中删除红色类(因此样式)并将其添加到新元素。这将允许一次只有一个元素为红色(在原始解决方案中,任何被点击的元素都将变为红色)。

Secondly - on the click event - this will now remove the red class (and therefore style) from the previously selected element and add it to the new element. This will allow only one element to be red at a time (in the original solution any element that was clicked would become red).

var els = document.getElementsByClassName('abc');
for (var i = 0; i < els.length; i++) {
  els[i].onclick = fun1;
}

function fun1() {
  var oldLink = document.getElementsByClassName('red')[0];
  if(oldLink) {oldLink.classList.remove('red')};
  this.classList.add('red');
}

.red {
 color:red;
}

<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>

这篇关于将事件侦听器绑定到具有相同类的多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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