Why do you need addEventListener?
Let’s take a look at a clip:
html code
<div id="box">Chasing Dreams</div>
Code with on
window.onload = function(){ var box = document.getElementById("box"); box.onclick = function(){ console.log("I am box1"); } box.onclick = function(){ box.style.fontSize = "18px"; console.log("I am box2"); }} Running result: "I am box2"I saw it, the second onclick overwrites the first onclick. Although in most cases we can use on to complete the results we want, sometimes we need to execute multiple identical events. It is obvious that if we cannot use on to complete what we want, then there is no need to guess. You must know, right! The addEventListener can bind the same event multiple times and will not overwrite the previous event.
Code with addEventListener
window.onload = function(){ var box = document.getElementById("box"); box.addEventListener("click",function(){ console.log("I am box1"); }) box.addEventListener("click",function(){ console.log("I am box2"); })} Running result: I am box1 I am box2The first parameter of the addEventListenert method is filled in the event name. Note that you do not need to write on. The second parameter can be a function. The third parameter refers to the process of the event handler in the bubble stage or the capture stage. If true represents the processing of the capture stage, if false represents the processing of the bubble stage, the third parameter can be omitted. In most cases, the third parameter does not need to be used. If the third parameter is not written, the default false is false.
Use of the third parameter
Sometimes this is the case
<body>
<div id="box">
<div id="child"></div>
</div>
</body>
If I add a click event to the box, there is no problem if I click the box directly, but if I click on the child element, how does it do it? (Execution order)
box.addEventListener("click",function(){ console.log("box");})child.addEventListener("click",function(){ console.log("child");}) Execution result: child boxThat is, the default event is performed in the order in which event bubbles.
If the third parameter is written as true, it will be performed in the order of execution of event capture.
box.addEventListener("click",function(){ console.log("box");},true)child.addEventListener("click",function(){ console.log("child");}) Execution result: box childEvent bubble execution process:
Start bubbling upward from the most specific element (the element you clicked on). Take our case above and the order of it is: child->box
Event capture execution process:
Start bubbling into the inside from the least specific element (the box on the outermost one). Take our case above and the order is: box->child
The above article comprehensively understands the difference between addEventListener and on is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.