JavaScript 饼图函数和回调仅显示数据库中的最后一个元素
JavaScript pie chart functions and callbacks displaying only last elements in database
我正在尝试创建动态数量的饼图,具体取决于我在测验中有多少问题,但是,创建图表的函数在 for 循环中,仅显示 1 个饼图,其中包含数据库中最后的数据.
var l = 0;
for (var j in quizs[i].quests) {
if (val == quizs[i].quests[j]["quizId"]) {
l = l + 1;
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
alert("before++" + quizs[i].quests[j]["question"]);
function drawChart() {
alert("in++" + quizs[i].quests[j]["question"]);
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById(l));
chart.draw(data, options);
}
}
}
例如 alert("in++" + quizs[i].quests[j]["question"]);
是数据库中的最后一个元素,欢迎任何回答。
google.charts.setOnLoadCallback
必须只支持一个回调。您应该将循环放在回调中,而不是尝试为每个循环迭代加载新的 Google 图表 API:
google.charts.setOnLoadCallback(() => {
var l = 0;
for (var j in quizs[i].quests) {
if (val == quizs[i].quests[j]["quizId"]) {
l = l + 1;
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById(l));
chart.draw(data, options);
}
}
});
google.charts.load('current', {
packages: ['corechart']
});
我正在尝试创建动态数量的饼图,具体取决于我在测验中有多少问题,但是,创建图表的函数在 for 循环中,仅显示 1 个饼图,其中包含数据库中最后的数据.
var l = 0;
for (var j in quizs[i].quests) {
if (val == quizs[i].quests[j]["quizId"]) {
l = l + 1;
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
alert("before++" + quizs[i].quests[j]["question"]);
function drawChart() {
alert("in++" + quizs[i].quests[j]["question"]);
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById(l));
chart.draw(data, options);
}
}
}
例如 alert("in++" + quizs[i].quests[j]["question"]);
是数据库中的最后一个元素,欢迎任何回答。
google.charts.setOnLoadCallback
必须只支持一个回调。您应该将循环放在回调中,而不是尝试为每个循环迭代加载新的 Google 图表 API:
google.charts.setOnLoadCallback(() => {
var l = 0;
for (var j in quizs[i].quests) {
if (val == quizs[i].quests[j]["quizId"]) {
l = l + 1;
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById(l));
chart.draw(data, options);
}
}
});
google.charts.load('current', {
packages: ['corechart']
});