1. First introduce the usage of the two:
1. Usage of on: Take onclick as an example
The first one:
obj.onclick = function(){ //do something.. }
The second one:
obj.onclick= fn; function fn (){ //do something... }
Third method: Use an anonymous function to pass parameters when function fn has parameters:
obj.onclick = function(){fn(param)}; function fn(param){ //do something.. }
cannot be written like this: Wrong writing: obj.onclick= fn(param):
Because the function written in this way will be executed immediately and will not wait for the click to trigger, pay special attention to
2. The usage of addEventListener:
Format:
addEventListener(event,funtionName,useCapture)
Parameters:
Writing method:
The first type:
obj.addEventListener("click",function(){ //do something }));
The second type, you can directly write the function name without parameters
obj.addEventListener("click",fn,fasle)); function fn(){ //do something.. }
Third type: When the function has parameters, you need to use an anonymous function to pass the parameters
obj.addEventListener("click",function(){fn(parm)},false);
2. The difference between the two
1. The on event will be overwritten by the subsequent on event
Take onclick as an example:
//obj是一个dom对象,下同//注册第一个点击事件 obj.onclick(function(){ alert("hello world"); }); //注册第二个点击事件 obj.onclick(function(){ alert("hello world too"); });
In the end there will be only Pop-up box output:
hello world too
2.addEventListener will not be overwritten.
//注册第一个点击事件 obj.addEventListener("click",function(){ alert("hello world"); })); //注册第二个点击事件 obj.addEventListener("click",function(){ alert("hello world too"); }));
This will output continuously:
hello world hello world too
3. Notes on addEventListener:
1. Special note that addEventListener is not compatible with IE9 and below. For IE9 and below, use attachEvent()
obj.attachEvent(event,funtionName);
Parameters:
event: event type (needs to be written as "onclick "Add on in front, this is different from addEventListener)
funtionName: method name (if you want parameters, you also need to use anonymous functions to pass parameters)
4. Event collection:
1. Mouse event:
2. Keyboard events:
5. Summary:
onXXX and addEventListener both add event listeners to dom elements so that they can execute corresponding code and operations after the event occurs. With them we realize page and user interaction.
Related learning recommendations: javascript video tutorial
The above is the detailed content of Analyze the difference between Js on and addEventListener principles and usage. For more information, please follow other related articles on the PHP Chinese website!