我有一个包含4个对象的data.json文件:a,b,c,d。
我手动声明了变量。
if name == "main":
for N in range(6):
a = array(N,N,N)
for i in range(N):
a[i,i,i] = 1
for i in range(N):
for j in range(N):
for k in range(N):
if i==j==k and a[i,j,k] == 1:
print(" \nYay! *a[{},{},{}] = 1 * ".format(i,j,k))
if a[i,j,k] == 1 and not i==j==k:
print(" \n+++ Crap!!! a[{},{},{}] = 1 +++ ".format(i,j,k))
现在,我想动态地创建它,以便它可以处理我的JSON文件中的所有对象,并且它不会中断 - 当我向JSON文件添加更多对象时。
所以在循环中,我尝试添加:
var chart_a = new google.visualization.PieChart(document.getElementById('sa-piechart-a'));
var chart_b = new google.visualization.PieChart(document.getElementById('sa-piechart-b'));
var chart_c = new google.visualization.PieChart(document.getElementById('sa-piechart-c'));
var chart_d = new google.visualization.PieChart(document.getElementById('sa-piechart-d'));
我从Ajax调用中获取了对象。
chart[object] = new google.visualization.PieChart($('#sa-piechart-'+ object.toLowerCase() )); // <---- I try to add this line
我不断获得var data = {};
var chart = {};
for (var object in objects) {
var total = objects[object].danger + objects[object].warning + objects[object].success ;
data[object] = google.visualization.arrayToDataTable([
['Piechart' , 'Number of Skills'],
['danger' , ( objects[object].danger/total ) * 100 ],
['warning' , ( objects[object].warning/total ) * 100 ],
['success' , ( objects[object].success/total ) * 100 ],
]);
//console.log( '#sa-piechart-' + object.toLowerCase() ); // Return #sa-piechart-a
chart[object] = new google.visualization.PieChart($('#sa-piechart-'+ object.toLowerCase() )); // <---- I try to add this line
}
// var chart_a = new google.visualization.PieChart(document.getElementById('sa-piechart-a'));
// var chart_b = new google.visualization.PieChart(document.getElementById('sa-piechart-b'));
// var chart_c = new google.visualization.PieChart(document.getElementById('sa-piechart-c'));
// var chart_d = new google.visualization.PieChart(document.getElementById('sa-piechart-d'));
任何提示/建议都将不胜感激!
答案 0 :(得分:1)
Container is not defined
表示找不到评论中提到的DOM元素。您需要动态创建元素,然后将它们传递给谷歌饼图。这样的事情应该做。
var el = document.getElementById('sa-piechart-' + object);
if (!el) {
el = document.createElement('div');
el.id = object;
document.body.appendChild(el); // <--- I added to body. Add to required element
}
chart[object] = new google.visualization.PieChart(el);
chart[object].draw(data[object]);
这是一个演示 http://jsfiddle.net/6M2sH/443/
一个更加漂亮的解决方案(使用jQuery)
var $el = $('#sa-piechart-' + object).length ? $('#sa-piechart-' + object) : $('<div id="#sa-piechart-' + object+'"></div>').appendTo('body');
chart[object] = new google.visualization.PieChart($el[0]);