【问题标题】:Value resetting when a method is called within the onload在 onload 中调用方法时重置值
【发布时间】:2010-08-27 02:37:04
【问题描述】:
window.onload = init;

function init(){
   initializeEventHandlers();
   getData(formatDate(new Date));
   gotoDate('today');
}

//scripts that manage the UI for tracker.aspx
var dCurrentDate, sCurrentDate, sCurrentDayData, stepsVal, chipsVal, dayValue, dateValue, caloriesVal;
var fCurrentValue = 0;
var bAnimating, bSliding = false;

   //scripts that manage the UI for tracker.aspx
    var dCurrentDate, sCurrentDate, sCurrentDayData, stepsVal, chipsVal, dayValue, dateValue, caloriesVal;
    var fCurrentValue = 0;
    var bAnimating, bSliding = false;

getData(d)
{
  steps = 5;
  calories = 10;
  chipsAmount = 3;
}


//I expect this to be 5+1, but it actually through an exception. I am wondering if its cause steps is not yet loaded. What can I do to make this actually 5 + 1.
steps + 1;

我从设置了一些值的 XML 加载数据。我面临的问题是,当我在 GetData 方法中设置值时。声明的变量在加载后失去了价值。我做错了什么以及如何使值保留

【问题讨论】:

  • 您是在异步加载数据吗?如果是这样,则在您尝试设置它们时这些值可能不存在,因此您应该与脚本同步加载它。否则我不确定我是否完全理解你的问题。
  • 是的,我正在同步加载
  • 问题主要是我需要在onload时设置变量,以便其他函数可以使用它们

标签: javascript xml ajax


【解决方案1】:

您要加载数据的变量是否在全局范围内定义?在您的 getData() 函数中,如果您将数据设置为 steps、calories 和 chipsAmount 变量,则在该函数之外将无法访问它们。您必须在函数外部定义这三个变量,以便它们在全局范围内。

【讨论】:

  • 在未使用 var 声明的函数中使用的变量归全局对象(即窗口)所有,并且确实可以在其他地方访问,无论它们是否已被全局声明
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 2018-08-18
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多