Vanilla JavaScript version of jQuery .click

后端 未结 7 664
孤城傲影
孤城傲影 2020-12-07 22:24

So maybe I\'m just not looking in the right places but I can\'t find a good explanation of how to do the equivalent of jQuery\'s

$(\'a\').click(function(){
          


        
7条回答
  •  青春惊慌失措
    2020-12-07 22:37

    I just stumbled upon this old question.

    For new browsers (find support here: https://caniuse.com/?search=querySelectorAll)

    My solution would be:

    function clickFunction(event) {
      // code here
    }
    
    for (let elm of document.querySelectorAll("a")) {
      elm.onclick = clickFunction;
    }
    

    This is optimized to not create a new function for each element.

    Will work on IE9 and up.

提交回复
热议问题