EventListener for a class?

后端 未结 4 409
离开以前
离开以前 2021-01-17 07:15

I have an EventListener that references an Id and it works well, the only problem is that i have at least a dozen places where this EventListener needs to reference so i don

4条回答
  •  佛祖请我去吃肉
    2021-01-17 07:28

    you can assign a class to each of these elements and use a for loop to iterate through and place a eventListener.

    var elements = document.querySelectorAll('.className');
    
    for (i = 0; i < elements.length; ++i) {
    
      elements[i].addEventListener('click', function() {
    
        // Do something amazing
    
      });
    
    }
    

    via: http://pencilscoop.com/2014/06/using-eventlisteners-on-multiple-elements

    or you could just add onclick to your elements individually

     Chart
    

提交回复
热议问题