简体   繁体   English

JQuery Event之外的变量范围

[英]Variable scope outside of JQuery Event

I keep getting undefined for quarterStr ? 我继续为quarterStr定义? I am trying to access it in the getNexthreeMonths function. 我试图在getNexthreeMonths函数中访问它。 So a month is chosen from a drop down menu and then I want to access the result in the getNexthreeMonths : 因此,从下拉菜单中选择一个月,然后我想访问getNexthreeMonths的结果:

getNextThreeMonths: function() {
  $("#date").on('change', function (e){
    var currentMonth = $(this).find('option:selected').attr('id');
    var currentMonth = parseInt(currentMonth);
    var qNum = Math.floor(currentMonth / 3);
    var qArr = ["Jan","Apr","Jul","Oct"];
    var quarterStr = qArr[ (qNum+1) % 4 ] + "," + qArr[ (qNum+2) % 4 ] + "," + qArr[ (qNum+3)%4 ];

  });
  console.log(quarterStr);
}

There are two reasons for this. 有两个原因。

First, the var in var quarterStr = means the variable is locally scoped to the anonymous function you pass as an argument to on() and can't be accessed outside that function. 首先, var in var quarterStr =表示变量本地作用于您作为参数传递给on()的匿名函数,并且不能在该函数外部访问。

Second, the value isn't assigned to quarterStr until the change event on the date element fires and that function is run. 其次,在date元素的change事件触发并运行该函数之前,该值不会分配给quarterStr You're trying to read the value just after you assign the event handler. 您在分配事件处理程序后尝试读取值。 There is no way that it will have changed by then, so it will always be undefined. 到那时它无法改变,所以它总是未定义的。

You need to rethink your logic. 你需要重新思考你的逻辑。 You can't use JavaScript to time travel and figure out what the user might do at some point in the future. 您不能使用JavaScript来计算时间并确定用户将来可能会做些什么。

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

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