我有以下代码,其中我遍历项目列表并创建动态div元素。然后,在每个循环结束时,我想使用google visualisations
创建条形图并将其附加到创建的divs
。但是,我收到以下错误。
未定义容器
我是google visualisations
的新手。我想知道这是否可行。以下是我的代码:
function drawBarChart() {
PAGES = _.keys(_.countBy(perct_by_page_COLL_vs_NCOLL, function(data) { return data.PAGE_SHORT; }));
$.each(PAGES, function(index, item){
$("#BLOQUES").append("<div class='" + item + "'></div>")
page_sub = $.grep(perct_by_page_COLL_vs_NCOLL, function(n, i) {return n.PAGE_SHORT === item;});
container = $("#BLOQUES").find('.' + item)
container.append('<div>' + page_sub[0].PAGE_TITLE + '</div>')
container.append("<div class='barchart'></div>")
x = page_sub[0]
a = x['PAGE_SHORT']
b = x['PERC_ALL']
c = x['PERC_NCOLL']
d = x['PERC_ALL']
var data = google.visualization.arrayToDataTable([
['PAGE_SHORT', 'PERC_ALL', 'PERC_COLL', 'PERC_NCOLL'], [a, b, c, d]
]);
var options = {
title: '',
chartArea: {width: '50%'},
hAxis: {
title: 'Total Population',
minValue: 0
},
vAxis: {
title: 'City'
}
};
var chart = new google.visualization.BarChart(container.find('.barchart'));
chart.draw(data, options);
});
}
答案 0 :(得分:1)
图表期待特定的dom元素
不是jquery引用,它基本上是一个元素数组
建议使用循环索引为图表元素
分配idcontainer.append("<div id='chart" + index + "' class='barchart'></div>")
然后使用id创建图表
var chart = new google.visualization.BarChart($('#chart' + index)[0]);
完整摘录......
function drawBarChart() {
PAGES = _.keys(_.countBy(perct_by_page_COLL_vs_NCOLL, function(data) { return data.PAGE_SHORT; }));
$.each(PAGES, function(index, item){
$("#BLOQUES").append("<div class='" + item + "'></div>")
page_sub = $.grep(perct_by_page_COLL_vs_NCOLL, function(n, i) {return n.PAGE_SHORT === item;});
container = $("#BLOQUES").find('.' + item)
container.append('<div>' + page_sub[0].PAGE_TITLE + '</div>')
container.append("<div id='chart" + index + "' class='barchart'></div>")
x = page_sub[0]
a = x['PAGE_SHORT']
b = x['PERC_ALL']
c = x['PERC_NCOLL']
d = x['PERC_ALL']
var data = google.visualization.arrayToDataTable([
['PAGE_SHORT', 'PERC_ALL', 'PERC_COLL', 'PERC_NCOLL'], [a, b, c, d]
]);
var options = {
title: '',
chartArea: {width: '50%'},
hAxis: {
title: 'Total Population',
minValue: 0
},
vAxis: {
title: 'City'
}
};
var chart = new google.visualization.BarChart($('#chart' + index)[0]);
chart.draw(data, options);
});
}