JavaScript function executing too soon

2019-01-29 14:05发布

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

    function myFonk(info) {
        $("#result").html(info);
    }

    function getText(text) {
        return function () {
            myFonk(text);
        }
    }

    $(document).ready(function () {
        $("#b1").click(getText("getText"));
        $("#b2").click(myFonk("myFonk"));
    });

3条回答
戒情不戒烟
2楼-- · 2019-01-29 14:41

Whenever we write the function name with () it calls that function instantly hence myFonk("myFonk") is not correct way..

Write in following manner.

function myFonk(info) {
    $("#result").html(info);
}

function getText(text) {
    return function () {
        myFonk(text);
    }
}

$(document).ready(function () {
    $("#b1").click(getText("getText"));
    $("#b2").click(function () {
        myFonk("myFonk")
    });
});
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-29 14:53

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")
    });
});
查看更多
等我变得足够好
4楼-- · 2019-01-29 15:06
$(document).ready(function () {
    $("#b1").click(getText("getText"));
});

What you're doing here is calling the function getText("getText") and passing the result of that call to $("#b1").click(). You don't want to pass the result of the function. What you want to do is to pass the function itself. So rewrite as,

$(document).ready(function () {
    $("#b1").click(function() {
        return getText("getText");
    });
});

If the function you were interested in had no parameters (let's say, for example, that you wanted to call a function hello(), with no parameters, you could do it the same way:

$(document).ready(function () {
    $("#b1").click(function() {
        return hello();
    });
});

... or you could simplify it:

$(document).ready(function () {
    $("#b1").click(hello);
});

Note: you're passing hello (the function itself), not hello() (which would execute the function immediately and return the result to the click() function.

查看更多
登录 后发表回答