美文网首页
6. Event Element Binding

6. Event Element Binding

作者: Time_Notes | 来源:发表于2023-09-01 16:27 被阅读0次

    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.

    相关文章

      网友评论

          本文标题:6. Event Element Binding

          本文链接:https://www.haomeiwen.com/subject/xpgmpdtx.html