How to add one event listener for all buttons

前端 未结 4 1970
孤城傲影
孤城傲影 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:32

    In this case, you could use a class instead of id to grab every button.

    
    
    
    
    

    And then in JS:

    const buttons = document.querySelectorAll('.btn')
    buttons.forEach(function(currentBtn){
      currentBtn.addEventListener('click', handleEvent)
    })
    

    You just loop over the buttons constant which hold a NodeList with all the buttons that were found. read about document.querySelectorAll

提交回复
热议问题