Why in Javascript event handler functions with parentheses?

后端 未结 4 2100
轻奢々
轻奢々 2020-12-09 12:25

Javascript gurus, look at this code:


        

        
相关标签:
4条回答
  • 2020-12-09 13:07

    All on-attributes on elements actually set inline Javascript, not a handler. So you're actually executing code there, in this case a function call. If you leave out the parentheses, it's just invalid code.

    Compare:

    <button onclick="alert('click!')">Click me!</button>
    
    0 讨论(0)
  • 2020-12-09 13:11

    Anything you put inside onclick="" will be wrapped with an implicit function. That is the actual event handler that will be called on click, any function call inside it needs the parentheses.

    0 讨论(0)
  • 2020-12-09 13:15

    Inline JS

    When you do an inline onclick handler like that, you're assigning a Javascript expression to run. So you need to execute the function.

    The expression could just as easily be onclick="handler();alert(2)" in which case its obvious that the function needs to be called, just like it would be if it were run from a javascript file.

    Binding a function to the click event

    If instead you attach the click event with javascript, you would be binding a function, so you just need to pass the function object.

    var btn = document.getElementById("btn");
    btn.addEventListener("click",handler);
    

    addEventListener sets the function object to be bound to the event so that it executes when the event is triggered. Since you're specifying a function object, rather than a string expression, the parentheses are not needed. In fact if you added them the function would execute immediatelly and the return value of the function would be bound to the event.

    Best Practice

    In general most people would advocate you bind events in javascript by binding a function handler rather than using inline JS. Its easier to debug, doesn't tightly bind your logic to the DOM, and is more flexible for dynamic pages. It also forces you to make any functions that you're calling global.

    Summary

    The key is the attribute points to a string that is evaluated as a JS expression, it is not the same as binding a function object to the event.

    0 讨论(0)
  • 2020-12-09 13:23

    Because onclick="handler" isn't JavaScript. It's an attribute of your tag. Yes, if this were JavaScript, you'd be able to pass in the function itself, but it's not; you're assigning a statement to be executed on click.

    The statement executed by onclick="handler" basically does this:

    <script>
    handler;
    </script>
    

    IE, nothing.

    0 讨论(0)
提交回复
热议问题