Home > Article > Web Front-end > Detailed explanation of the difference between click and onclick
This time I will give you a detailed explanation of the difference between click and onclick, and what are the precautions for using click and onclick. The following is a practical case, let's take a look.
The click of native javascript is explained in w3c as the DOM button object, which is also the html DOM click() method, which can simulate a mouse click on the button.
button object Represents a button in an HTML document. The button element has no default behavior, but must have an onclick event handler in order to use it.
Syntax: buttonObject.click()
<html> <head> <script type="text/javascript"> function clickButton() { document.getElementById('button1').click() } function alertMsg() { alert("Button 1 was clicked!") } </script> </head> <body onload="clickButton()"> <form> <input type="button" id="button1" onclick="alertMsg()" value="Button 1" /> </form> </body> </html>
onclick is an event, Event object . JavaScript objects that support this event: button, document, checkbox, link, radio, reset, submit
HTML DOM Event object, representing the status of the event, such as the element in which the event occurred, the status of the keyboard keys, and the mouse position, mouse button state. Events are often used in conjunction with functions, which are not executed until the event occurs!
<html> <body> Field1: <input type="text" id="field1" value="Hello World!"><br /> Field2: <input type="text" id="field2"> <br /> 点击下面的按钮,把 Field1 的内容拷贝到 Field2 中: <br /> <button onclick="document.getElementById('field2').value=document.getElementById('field1').value">Copy Text</button> </body> </html>
Difference
As mentioned earlier, click is a method and onclick is an event.
The most fundamental question is, what is the difference between methods and events?
The difference is:
1. The event name usually starts with on;
2. The method is called directly by the programmer writing a statement, that is Display call; [Onclick event can be triggered]
3. The event does not need to be called by the programmer, but the programmer must write a function and assign the function to the corresponding event, and the call is in the corresponding event when triggered. [Tell the browser what to do when the mouse clicks] So the calling order is: first the method and then the event.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Use JS to manipulate images and leave only black and white
##Use react, redux, react-redux
The above is the detailed content of Detailed explanation of the difference between click and onclick. For more information, please follow other related articles on the PHP Chinese website!