How to add a onclick event to an element using javascript

前端 未结 7 1113
忘掉有多难
忘掉有多难 2020-12-04 02:03

I have created an element using document.getElementsByClassname, and would like to add a onclick event to this element, so that when someone clicks on this element onclick f

7条回答
  •  情深已故
    2020-12-04 02:11

    You can use an event delegation or DOMNode.matches.

    document.addEventListener('click', function(e) {
       if (e.target.className == 'classname') // if (e.target.matches('.classname'))
       {
           //do something
       }
    });
    

提交回复
热议问题