How to add one event listener for all buttons

前端 未结 4 1961
孤城傲影
孤城傲影 2020-12-19 12:02

How do I add an event listener to multiple buttons and get the value of each one depending on the one clicked. Eg:

4条回答
  •  鱼传尺愫
    2020-12-19 12:24

    Like Lucas's answer, this version will use classes instead of ID to select each button, and it will use a basic for loop.

    
    
    
    
    

    The JS

    var buttons = document.querySelectorAll(".btn").length;
    
    for (var i = 0; i < buttons ; i++) {
        document.querySelectorAll(".btn")[i].addEventListener("click", function() {
            alert("Button Clicked");
        });
    }
    

提交回复
热议问题