Binding an event listener to multiple elements with the same class

后端 未结 3 1052
臣服心动
臣服心动 2020-12-20 07:30

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

first
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-20 07:57

    .onclick does not expect to receive a string, and in fact you don't need an extra function at all.

    However, to assign it to each element, use a loop, like I'm sure you must have learned about in a beginner tutorial.

    var els = document.getElementsByClassName('abc');
    for (var i = 0; i < els.length; i++) {
      els[i].onclick = fun1;
    }
    
    function fun1() {
      this.style.color = "red";
    }
    first
    second
    third

提交回复
热议问题