简体   繁体   中英

html dom adding javascript functions

What is the difference between these two:

document.form1.colorButton.onclick = setBGColor;`

and

<input name="colorButton" type="button"
       value="Change background color"
       onclick="setBGColor();"/>`

When adding it to the attribute there are () but when using the DOM no (). Why is this?

Any referencea to official documentation would help.

In the .onclick version, you are directly assigning a reference to a JS function reference to the .onclick property. It would be an error to supply the parentheses because that would result in the function being called immediately and its result being assigned to the event handler.

In the "inline" DOM0 method, the resulting code is more like:

document.form1.colorButton.onclick = function onclick(event) {
    setBGColor();
}

and in fact this is exactly what you'd see in a Chrome console if you used the inline method and then looked at the value of document.form1.colorButton.onclick .

To explain further, the body of the onclick attribute is wrapped up inside a new function and then the reference to that is assigned to the property. You must supply the parentheses otherwise the setBGColor() function would not be invoked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM