The event handler
has three ways to bind an event handler to an element.
A, HTML properties
<a onclick= "alert (' click ')" ></A>
This is used to directly invoke Event,this in the function to point to the current element. But this approach is generally not applicable.
B, JS element properties
This way of compatibility is good, all browsers are supported. But there is a compatibility issue. That is, the Ie8-event object is passed in as a property of window rather than as a parameter. So write it like this. <!doctype html> document.getElementById ( ' a '). onclick = function = Event | | window.event; alert (event); } </script></body>
c, DOM2 event binding
mainly refers to the elements of the AddEventListener () and RemoveEventListener (). The former binds and the latter is removed.
Both functions have three parameters,
The third is a Boolean value, and true means that the handler function is called during the capture phase. False indicates that the handler function is called during the bubbling phase.
<!doctype html> document.getElementById (' a '). AddEventListener (' click ', function(event) { alert (event); },false)
If you want to unbind, someone might:
<!doctype html> document.getElementById ( ' a '). AddEventListener (' click ', function false ) document.getElementById ( ' a '). RemoveEventListener (' click ', function false ) </script></ Body>
but this is not going to be successful. Because the function is an object, two anonymous functions are different objects, not equal. So there's no way to unbind an anonymous function. Can only think of the following, a function of a name.
<!doctype html>var handler = f Unction ' a '). AddEventListener (' click ', Handler,false ' a '). RemoveEventListener (' Click ', Handler, false ) </script></body>
Ie8-'s browser does not support DOM2-level events, but there are similar methods attachevent () and DetachEvent (), and the usage is the same, just because ie8-has only bubbling process so there is no third argument. There is also a first parameter to add ' on ', such as the Click event is ' onclick '. In addition, this in the function points to window.