JavaScript function executing too soon

后端 未结 3 802
离开以前
离开以前 2020-12-22 13:28

In the example below, myFonk is called instantly; it doesn\'t wait for the click event. Why not?

    function myFonk(info) {
        $(\"#result         


        
3条回答
  •  青春惊慌失措
    2020-12-22 14:15

    It's because you're not passing a reference to the functions. You're calling the functions and using the results as the event handlers for click.

    This will fix that for you...

    function myFonk(info) {
        $("#result").html(info);
    }
    
    function getText(text){
        return function() {
            myFonk(text);
        }
    }
    
    $(document).ready(function() {
        $("#b1").click(function() {
            getText("getText")
        });
        $("#b2").click(function() {
            myFonk("myFonk")
        });
    });
    

提交回复
热议问题