简体   繁体   English

jQuery 选择器回调 function 中的全局变量 Javascript

[英]Global Javascript vars in jQuery selector callback function

I am trying to call Ajax with jQuery and need to pass a variable that is set with PHP on the page load, to two separate functions to either move my calendar forward or backwards by the months.我正在尝试使用 jQuery 调用 Ajax,并且需要将在页面加载时使用 PHP 设置的变量传递给两个单独的函数,以按月向前或向后移动我的日历。

var ajax_load = "Loading...",
    loadUrl = "calendar_backend.php",
    month = parseInt(<?php echo $month ?>);
    console.log(month);
    month = <?php echo $month ?>;

$("#calendar_box").on("click",'#next_month',function(){  
    console.log(month);
    $("#calendar")  
        .html(ajax_load)  
            .load(loadUrl, "month=" + month + "&go=next");
    var month = ++month;

    console.log(month);
});

$("#calendar_box").on("click",'#previous_month',function(){  
    $("#calendar")  
        .html(ajax_load)  
            .load(loadUrl, "month" + month + "&go=previous");  
    var month = --month;
});

I have the console calls in there to try to debug this and I get 4 from the first.log() undefined from the second one, and NaN from the third.我在那里有控制台调用来尝试调试它,我从第二个未定义的 first.log() 中得到 4,从第三个中得到 NaN。 From those three I can see that the variable is not getting passed into the.on() handler function.从这三个中我可以看到变量没有传递到 the.on() 处理程序 function。

The calender generating page is included_once on the index page and then the AJAX would be used to regenerate the correct data for the month.日历生成页面在索引页面上包含一次,然后 AJAX 将用于重新生成该月的正确数据。 I need the month passed in the get string to know how far from the current month i need to offset.我需要在获取字符串中传递的月份才能知道我需要抵消当前月份的距离。

Thanks for the help!!谢谢您的帮助!!

Simply don't use the var keyword inside the function body.不要在 function 正文中使用var关键字。 var will instanciate a new variable inside the success function . var将在success function中实例化一个新变量。 And you using the decress/incresse operator wrong, its only month++;而且您使用的递减/递增运算符错误,只有month++; and month--;month--;

var ajax_load = "Loading...",
    loadUrl = "calendar_backend.php",
    month = parseInt(<?php echo $month ?>);
    console.log(month);
    month = <?php echo $month ?>;

$("#calendar_box").on("click",'#next_month',function(){  
    console.log(month);
    $("#calendar")  
        .html(ajax_load)  
            .load(loadUrl, "month=" + month + "&go=next");
    month++; // Removed var and incressing

    console.log(month); 
});

$("#calendar_box").on("click",'#previous_month',function(){  
    $("#calendar")  
        .html(ajax_load)  
            .load(loadUrl, "month" + month + "&go=previous");  
    month--; // Removed var and decressing
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM