How do you catch a click event with plain Javascript?

后端 未结 6 1607
挽巷
挽巷 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 10:31

    I would recommend going with addEventListener instead of assigning the handler function directly.

    var div = document.getElementById('test');
    div.addEventListener('click', function(){ 
        console.log('CLICKED');
    });
    

    There are several reasons for that by I am going to name those I find the most important:

    1. You can't mistakenly add event listener to a non-DOM object with addEventListener - your code would fail instead of quietly assigning onclick function to some object
    2. You can attach only one (without additional code manipulation for every handler that you want to add) event listener with onclick - something that might prove limiting

提交回复
热议问题