6. Event Element Binding

2023-09-01  本文已影响0人  Time_Notes

Rule #5: HTML Event Element Binding in JavaScript

In HTML event handlers, this binds to the HTML elements that receive the event.

<button onclick="console.log(this)">Click Me!</button>

The is the output log in the console when you click on the button:

"<button onclick='console.log(this)'>Click Me!</button>"

You can change the button style using the this keyword, like this:

<button onclick="this.style.color='teal'">Click Me!</button>


But be mindful when you call a function on the button click and use this inside that function.

<button onclick="changeColor()">Click Me!</button>

and the JavaScript:

function changeColor(){this.style.color='teal';}

The above code won't work as expected. As we have seen in the Rule 4, here this will be bound to the global object (in the 'non-strict' mode) where there is no style object to set the color.

上一篇下一篇

猜你喜欢

热点阅读