Binding an event listener to multiple elements with the same class

后端 未结 3 1037
臣服心动
臣服心动 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";
    }
    <div class="abc">first</div>
    <div class="abc">second</div>
    <div class="abc">third</div>

    0 讨论(0)
  • 2020-12-20 08:03

    This works:

    <body>
    <div class="abc">first</div>
    <div class="abc">second</div>
    <div class="abc">third</div>
    <script>
    var elements = document.getElementsByClassName('abc');
    
    for(var i = 0, max = elements.length; i < max; i += 1) {
      var clickedElement = elements[i];
      clickedElement.onclick=function (){
        fun1(this);
      };
    }
    
    function  fun1(element){
      element.style.color="red"; 
    }
    </script>
    </body>

    0 讨论(0)
  • 2020-12-20 08:06

    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.

    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>

    0 讨论(0)
提交回复
热议问题