Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the difference between onclick and click in JavaScript

Shulou Source: shulou.com Published: 2022-06-03 05:24:21 11月22日 Update

Editor to share with you what is the difference between onclick and click in JavaScript, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Why do I need addEventListener?

Let's first take a look at a clip:

test

Use the code of on:

Windwo.onload = function () {var box = document.getElementById ("box"); box.onclick = () = > console.log ("I am box1"); box.onclick = () = > console.log ("I am box2");} / / result: I am box2

You see, the second onclick event overrides the first onclick, although in most cases we can achieve the desired effect with on, but sometimes we need to execute multiple identical events, which is obviously impossible with on. However, you can use addEventListener to bind the same event multiple times without overwriting the previous event.

Use addEventListener code _ window.onload = function () {var box = document.getElementById ("box"); box.addEventListener ("click", () = > console.log ("I am box1"); box.addEventListener ("click", () = > console.log ("I am box2");} / / run result: I am box1 / / I am box2

The first parameter of the addEventListener method enters the event name. Note that there is no need to write on, the second parameter can be a function, and the third parameter refers to the bubbling phase or the capture event handler. If true represents the capture phase processing, if false represents the bubbling phase processing, the third parameter can be omitted. In most cases, the third parameter does not need to be used, and the default false is not written for the third parameter.

The use of the third parameter

Sometimes it goes like this:

If I add cclick time to box, there's nothing wrong with clicking box directly, but how does it work if I click on the child element?

Box.addEventListener ("click", () = > console.log ("box")); child.addEventListener ("click", () = > console.log ("child")); / / execution result: child-> box

That is, the default is in the order in which the event bubbles are executed.

If the third parameter is written as true, it follows the order in which the event capture is executed.

These are all the contents of this article entitled "what's the difference between onclick and click in JavaScript". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Event parameter three situation article result stage processing code representative content most order run obvious same not much that is elements Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Linux MySQL Shulou Tech Info Redmi