Why is this javascript function running without being called?

前端 未结 4 1392
暗喜
暗喜 2020-12-19 11:26
$(document).ready(SetupButtonClicks());

function SetupButtonClicks() {
    $(\'#btnJavaPHP\').click(DoPHPStuff());
}

function DoPHPStuff() {
    //stuff
}
<         


        
相关标签:
4条回答
  • 2020-12-19 11:36

    Change your SetupButtonClicks function:

    $('#btnJavaPHP').click(DoHPStuff);
    

    The way you've got it coded, you're telling Javascript to call the function, not to use it as the "click" handler. The parentheses are an operator that causes a function to be called.

    0 讨论(0)
  • 2020-12-19 11:39

    Remove the ().

    By writing $(document).ready(SetupButtonClicks()), you are calling SetupButtonClicks and passing its return value to ready.
    Similarly, by writing $('#btnJavaPHP').click(DoPHPStuff()), you are calling DoPHPStuff (immediately) and passing whatever it returns to click().

    You need to pass the functions themselves by writing $(document).ready(SetupButtonClicks) and $('#btnJavaPHP').click(DoPHPStuff).

    0 讨论(0)
  • 2020-12-19 11:56

    With the exception of a function declaration, a pair of parentheses following a function's identifier causes the function to execute. Examples:

    // function declaration; function not executed
    function SetupButtonClicks() {
    
    }
    
    // function executed
    SetupButtonClicks();
    
    // function not executed
    SetupButtonClicks;
    
    0 讨论(0)
  • 2020-12-19 11:57
    function DoPHPStuff() {
        //stuff
    }
    
    function SetupButtonClicks() {
        $('#btnJavaPHP').click(DoPHPStuff);
    }
    
    $(document).ready(SetupButtonClicks);    
    
    0 讨论(0)
提交回复
热议问题