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?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
I would recommend going with
addEventListener
instead of assigning the handler function directly.There are several reasons for that by I am going to name those I find the most important:
addEventListener
- your code would fail instead of quietly assigningonclick
function to some objectonclick
- something that might prove limitingDEMO: http://jsfiddle.net/e9jZW/1/
By adding an event listener or setting the
onclick
handler of an element: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.
I usaly create a kind of global event handler, very powerful, you can capture className, of the event "types" nodeTypes, you name it, i hope people will find this useul
Here is an interesting article about that, i used the same approach some times, basically, you add the event handler to
window
. http://mislav.uniqpath.com/js/handling-events-on-elements/