为什么这个变量不起作用?Jquery

Why this is variable does not work? Jquery

本文关键字:Jquery 不起作用 变量 为什么      更新时间:2023-09-26

我正在写下面的代码,它基本上将当前日期的数据带到一个PHP文件中,以便在jQuery中处理。直到这里一切都很好。但我不明白为什么在total变量选择了来自PHP文件的值之后,我不能有一个新的值。

day.each(function () {
        var $this = $(this);
        var the_index = $this.index();
        var the_date = $this.find('h3.date').html().substr(0,2);
        var the_day = $this.find('h3.day');
        /*THIS VARIABLE*/   
        var total = 0;
        $.get('trd/datetime.php', function (date) {
            if(that.hasClass('list-'+date.day)) {
                weekList.find('.item.list-'+date.day).addClass('active');
            }
            total = date.firstDate;
        }, 'json');
        console.log(total);

    });

我不知道我的英语是否有帮助,但是,请告诉我我做错了什么!

谢谢。

.get调用是异步的——它内部的东西在您的console.log语句之后运行

您可能想要使用回调,从.get处理程序内部调用:

$.get('trd/datetime.php', function (date) {
    // ...
    callback(total);
}, 'json');
function callback(total) {
    console.log(total);
}