How do you catch a click event with plain Javascript?

后端 未结 6 1609
挽巷
挽巷 2021-01-31 10:11

I know that when using jQuery you can do $(\'element\').click(); to catch the click event of an HTML element, but how do you do that with plain Javascript?

6条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 10:36

    By adding an event listener or setting the onclick handler of an element:

    var el = document.getElementById("myelement");
    
    el.addEventListener('click', function() {
      alert("Clicked");
    });
    
    // ... or ...
    
    el.onclick = function() {
      alert("Clicked");
    }
    

    Note that the even listener style allows multiple listeners to be added whereas the callback handler style is exclusive (there can be only one).

    If you need to add these handlers to multiple elements then you must acquire them as appropriate and add them to each one separately.

提交回复
热议问题