[英]Javascript function is being called on page load
My javascript switchDiv
function is being called on page load, when I don't want it to. 我的javascript
switchDiv
函数在页面加载时被调用,当我不想要它时。 When its called, it goes through the switch statement and does each of the cases, except the default. 当它被调用时,它会通过switch语句执行每个案例,除了默认情况。 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
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. 当然,在这种情况下你不能使用第一个,因为
switchDiv
本身有一个参数。 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: 但是,由于您多次这样做,您可能需要一个辅助函数,如“createHandler”或其他东西:
function createHandler(num) {
return function() { switchDiv(num); };
}
$("#be-button").on("click", createHandler(1));
$("#red-button").on("click", createHandler(2));
// etc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.