更改全局 JavaScript 变量的值
我试图更改 javascript 函数内的全局变量的值,但是,该值似乎没有被采用,我不确定为什么。 (诚然,我不是一个有经验的 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});
}
谢谢!
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. (Admittedly, I am not an experienced javascript person.) Here is my code:
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
getJSON
是异步的。改为这样做:问题是
getJSON
立即返回。只有稍后,当请求完成时,才会调用您的回调。与此同时,chart.draw
可能已经运行。通过将此代码移动到回调函数中,我们确保它在正确的时间运行。另请注意,我们可以消除全局。getJSON
is asynchronous. Do this instead:The issue is that
getJSON
returns immediately. Only later, when the request completes, is your callback called. In the meantime,chart.draw
may have already run. By moving this code into the callback function, we ensure it runs at the right time. Also note that we can eliminate the global.