出于某种原因,我的jQuery函数在页面加载时运行,而不是在单击时运行。这是一个例子:http://jsfiddle.net/KRvvg/
以下是代码:
var month = 'February';
var year = 2013;
$(document).ready(function () {
$('#moveMonthForward').click(moveMonthForwardFunction(month, year));
function moveMonthForwardFunction(month, year) {
var NextMonth = findNextMonth(month, year);
console.log('index.php?Year=' + NextMonth.Year + '&Month=' + NextMonth.Month);
}
function findNextMonth(CurrentMonth, CurrentYear) {
switch (CurrentMonth) {
case 'January':
var NextMonth = { 'Month': 'February', 'Year': CurrentYear };
break;
case 'February':
var NextMonth = { 'Month': 'March', 'Year': CurrentYear };
break;
case 'March':
var NextMonth = { 'Month': 'April', 'Year': CurrentYear };
break;
case 'April':
var NextMonth = { 'Month': 'May', 'Year': CurrentYear };
break;
case 'May':
var NextMonth = { 'Month': 'June', 'Year': CurrentYear };
break;
case 'June':
var NextMonth = { 'Month': 'July', 'Year': CurrentYear };
break;
case 'July':
var NextMonth = { 'Month': 'August', 'Year': CurrentYear1 };
break;
case 'August':
var NextMonth = { 'Month': 'September', 'Year': CurrentYear };
break;
case 'September':
var NextMonth = { 'Month': 'October', 'Year': CurrentYear };
break;
case 'October':
var NextMonth = { 'Month': 'November', 'Year': CurrentYear };
break;
case 'November':
var NextMonth = { 'Month': 'January', 'Year': CurrentYear };
break;
case 'December':
var NextMonth = { 'Month': 'January', 'Year': CurrentYear + 1 };
break;
}
return NextMonth;
}
});
答案 0 :(得分:7)
您不是将回调moveMonthForwardFunction
引用传递给click方法,而是调用moveMonthForwardFunction
方法并将其返回的值作为单击处理程序传递。
您应该将函数引用传递给click方法,如下所示
$('#moveMonthForward').click(function(){
moveMonthForwardFunction(month, year)
});