简体   繁体   English

更改全局javascript变量的值

[英]Changing value of global javascript variable

I'm attempting to change the value of a global variable inside a javascript function, however, the value does not seem to be taken, and I'm not sure why. 我正在尝试更改javascript函数中的全局变量的值,但是,该值似乎没有被采用,而且我不确定为什么。 (Admittedly, I am not an experienced javascript person.) Here is my code: (诚​​然,我不是一个有经验的javascript人。)这是我的代码:

var title_chart = "";

google.load("visualization", "1", {packages:["corechart"]});

google.setOnLoadCallback(drawChart);

function drawChart() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Country');
  data.addColumn('number', 'Number of Entries');

  jQuery.getJSON('/data/stats.json', function(chart_data) {
    title_chart = chart_data.chart_title;
    jQuery.each(chart_data.stats, function(index, value){
      data.addRows(1);
      data.setValue(index, 0, value.chart_label);
    });
  });

  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 450, height: 300, title: title_chart});

}

Thanks! 谢谢!

getJSON is asynchronous. getJSON是异步的。 Do this instead: 改为这样做:

jQuery.getJSON('/data/stats.json', function(chart_data) {
  var title_chart = chart_data.chart_title;
  jQuery.each(chart_data.stats, function(index, value){
    data.addRows(1);
    data.setValue(index, 0, value.chart_label);
  });

  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 450, height: 300, title: title_chart});
});

The issue is that getJSON returns immediately. 问题是getJSON立即返回。 Only later, when the request completes, is your callback called. 只有在请求完成后,才会调用您的回调。 In the meantime, chart.draw may have already run. 同时, chart.draw可能已运行。 By moving this code into the callback function, we ensure it runs at the right time. 通过将此代码移到回调函数中,我们确保它在正确的时间运行。 Also note that we can eliminate the global. 还要注意,我们可以消除全局。

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

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