Javascript function is being called on page load

[亡魂溺海] 提交于 2021-02-07 13:12:33

问题


My javascript switchDiv function is being called on page load, when I don't want it to. When its called, it goes through the switch statement and does each of the cases, except the default. Anybody know how to fix this?

$(document).ready(function() {
$("#be-button").on("click", switchDiv(1));
$("#red-button").on("click", switchDiv(2));
$("#green-button").on("click", switchDiv(3));
$("#blue-button").on("click", switchDiv(4));
});

var switchDiv = function (mapNum) {
    console.log(mapNum);
    switch(mapNum) {
    case 1:
        $("#be-data").show();
        $("#red-data").hide();
        $("#green-data").hide();
        $("#blue-data").hide();
        break;
    case 2:
        $("#be-data").hide();
        $("#red-data").show();
        $("#green-data").hide();
        $("blue-data").hide();
        break;
    case 3:
        $("#be-data").hide();
        $("#red-data").hide();
        $("#green-data").show();
        $("blue-data").hide();
        break;
    case 4:
        $("#be-data").hide();
        $("#red-data").hide();
        $("#green-data").hide();
        $("blue-data").show();
        break;
    default:
        $("#be-data").show();
        $("#red-data").hide();
        $("#green-data").hide();
        $("#blue-data").hide();
}
}

回答1:


You are executing the functions, rather than passing them as parameters. Ie, you need to distinguish between passing a function:

function myFunc() { }
$("selector").on("click", myFunc);    // "myFunc" is the handler

And executing a function:

function myFunc() { }
$("selector").on("click", myFunc());  // execute "myFunc" -- its return value is the handler

Of course, you can't use the first in this case, since switchDiv itself has a parameter. One way to get around this is to wrap it in an anonymous function:

$("#be-button").on("click", function() { switchDiv(1); });

Since you're doing this multiple times, however, you will probably want a helper function like "createHandler" or something:

function createHandler(num) {
    return function() { switchDiv(num); };
}

$("#be-button").on("click", createHandler(1));
$("#red-button").on("click", createHandler(2));
// etc


来源:https://stackoverflow.com/questions/19503943/javascript-function-is-being-called-on-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!