Onclick and addeventlistener can be divided:
Inline eventsAnd
Event Listeners
Event Listeners (addeventlistener and IE's attachevent)Similarities: all are time listeners. The differences are as follows:
1. Differences in browser usage
Addeventlistener:Many browsers support addeventlistener (ie9 and later are also supported). The usage is as follows: var target = Document. getelementbyid ("test ");
Target. addeventlistener ('click', test,
False);
Function Test (){
Alert ("test ");
}
Attachevent:In IE, an event listener similar to addeventlistener is provided: attachevent. Many versions of IE are supported, I have tested the IE6-10. The usage is as follows: var target = Document. getelementbyid ("test ");
Target. attachevent ('onclick', test );
Function Test (){
Alert ("test ");
}
2. parameter differencesIn addition to browser differences, addeventlistener and attachevent also have parameter differences. There are 3rd parameters in addeventlistener, but not in attachevent. The 3rd parameters are passed as false or true. This parameter is optional. The default value is false. False -- indicates that event processing will be executed in the bubble stage. True -- indicates that event processing will be executed in the capture phase. In theory, event listeners (addeventlistener and IE's attachevent) can infinitely add event listening to an element. The actual application constraint is the client memory limit, which varies with each browser.
Inline events (HTML onclick = "" Property and element. onclick)Usage: 1. <a id = "testing" href = "#" onclick = "alert ('did stuff inline');"> click me </a> 2. <a id = "test" href = "#"> click me </a> var element = document. getelementbyid ('test ');
Element. onclick = function () {alert ('did stuff #1 ');};
Inline eventsAnd
Differences between event listeners:
Event Listeners can add countless (theoretically) events,
Inline events can only add one event, and the following will overwrite the preceding event. For example:
<A id = "test" href = "#"> click I </a> var element = Document. getelementbyid ('test ');
Element. onclick = function () {alert ('did stuff # 1') ;}; element. onclick = function () {alert ('did stuff # 2') ;}; the result is: did stuff #2. the following form is recommended: function addevent (element, evnt, funct ){
If (element. attachevent)
Return element. attachevent ('on' + evnt, funct );
Else
Return element. addeventlistener (evnt, funct, false );
}
Addevent (
Document. getelementbyid ('mymeta '),
'Click ',
Function () {alert ('Hi! ');}
);
Differences between onclick and addeventlistener