本文介绍了页面加载时调用 Javascript 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 javascript switchDiv 函数在页面加载时被调用,但我不希望它这样做.当它被调用时,它会通过 switch 语句并执行每种情况,默认情况除外.有人知道如何解决这个问题吗?

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();
}
}

推荐答案

您正在执行函数,而不是将它们作为参数传递.即,你需要区分传递一个函数:

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

并执行一个函数:

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

当然,在这种情况下你不能使用第一个,因为 switchDiv 本身有一个参数.解决此问题的一种方法是将其包装在匿名函数中:

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); });

但是,由于您多次执行此操作,因此您可能需要一个像createHandler"之类的辅助函数:

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

这篇关于页面加载时调用 Javascript 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:23