Javascript jQuery:如何在更新时返回函数外部的值?(return语句不能执行此操作)

Javascript jQuery:如何在更新时返回函数外部的值?(return语句不能执行此操作),javascript,jquery,Javascript,Jquery,JavaScript/jQuery初学者提出的问题: 我将实际问题放入代码注释中,以使其非常清楚: $(“文档”).ready(函数(){ var时间戳; $(“#开始日期”)。日期选择器({ //下面是更新var时间戳 //每次用户通过日期选择器选择日期时 onSelect:函数(e){ var dateAsObject=$(this).datepicker(“getDate”);//getDate方法 timestamp=dateAsObject.getTime();//用户选择的日期的时

JavaScript/jQuery初学者提出的问题:

我将实际问题放入代码注释中,以使其非常清楚:

$(“文档”).ready(函数(){
var时间戳;
$(“#开始日期”)。日期选择器({
//下面是更新var时间戳
//每次用户通过日期选择器选择日期时
onSelect:函数(e){
var dateAsObject=$(this).datepicker(“getDate”);//getDate方法
timestamp=dateAsObject.getTime();//用户选择的日期的时间戳
日志(“用户选择:”+时间戳);
返回时间戳;
}
});
//我如何在这里得到timestamp的值,
//每次函数外的值
//函数内部的时间戳更改?
日志(“测试:+时间戳”);
//为什么上面的代码行没有更新/输出任何内容
//当函数内的时间戳值发生变化时
//我如何让它在这里工作/更新,在功能之外?
});

选择一个日期:

它没有改变,因为您已经调用了
console.log(“test:+timestamp”)更改日期之前。。。。让我们看看你的代码到底在做什么

$("document").ready(function() {
    var timestamp;
    //1- initialize date picker
    $("#startDate").datepicker({
        //2- add handler function only when select happens
        onSelect: function(e) {
            //4- the code below will be executed only when you select date
            var dateAsObject = $(this).datepicker("getDate"); //the getDate method
            timestamp = dateAsObject.getTime(); // timestamp of the date selected by user
            console.log("user selected: " + timestamp);
            return timestamp;
        }
    });
    //3- console log the value of timestamp.... this is still undefined because you still didn't select any date 
    //this line will not be called again after a data select
    console.log("test: " + timestamp);
});
检查下面的代码,我会添加一个间隔,每1秒记录一次时间戳。。。然后,您将能够在选择后看到新更新的时间戳

这只是为了澄清

$("document").ready(function() {
        var timestamp;
        //1- initialize date picker
        $("#startDate").datepicker({
            //2- add handler function only when select happens
            onSelect: function(e) {
                var dateAsObject = $(this).datepicker("getDate"); //the getDate method
                timestamp = dateAsObject.getTime(); // timestamp of the date selected by user
                console.log("user selected: " + timestamp);
                return timestamp;
            }
        });
        //3- now we set a timer to log timestamp every 1 second it will keep logging undefined until you select a date
        setInterval(function(){
                console.log("test: " + timestamp);
            } , 1000);
    });

@Andreas的可能副本谢谢你的链接,我不知道这个问题与异步调用有关(但我猜是这样)。我目前正在研究那个大线程中的响应,我几乎可以肯定那里的响应/信息将帮助我提高对JavaScript的理解和技能。好的,但是调用console.log(“test:+timestamp”)的魔术是什么;在数据选择之后再次?有jQuery特定的东西吗?我该怎么做呢?(很抱歉我是这样一个傻瓜)我编辑了代码,每1秒记录一次时间戳。。。但问题是您想在哪里使用时间戳。。。我想你只是想测试一下它是否被改变了,而且已经改变了。。。现在,您想在哪里使用它?P.S.刚刚看到您添加了间隔以每1秒记录一次时间戳。这是获得更新值的唯一方法吗?或者这只是最简单的方法?我想在另一个函数中使用时间戳。因此,timestamp的值将更改另一个函数的输出。timestamp已在代码中更新。。。。计时器只是为了向您证明,在您选择日期后,计时器已更改。。。。是的,如果您现在在另一个函数中使用timestamp,它应该选择更新的函数。。。。您不需要计时器
setInterval
,因为我已经提到了它只是为了澄清