我在基于JSON表(作为数据源)的包装器中有一个谷歌图表
var data = new google.visualization.DataTable(<?=$jsonTableA>);
如何通过单击按钮添加具有静态值的列?
我的意思是我将有一个变量(让我们假设该变量的值为4)如果JSON表有5行,则新数据中的所有五行都将具有&# 34; 4&#34;在该列中...如果JSON表有20行,则新数据中的所有20行将具有&#34; 4&#34;在该栏目中。
答案 0 :(得分:1)
for (var i = 0; i < dataTable.getNumberOfRows(); i++)
结合dataTable.setCell()
应该可以解决问题:
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
var addStatic; // global variable to hold click function
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2013', 1000, 400],
['2014', 1170, 460],
['2015', 660, 1120]
]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data);
// this function adds a colmn and sets a constant value in each row of that column,
// independently of the number of rows in the table
// then redraw the chart.
// no var: the addStatic variable must be global for the button's click handler to access it
addStatic = function() {
var staticValue = Math.random() * 1000;
data.addColumn('number', 'Constant');
for (var i = 0; i < data.getNumberOfRows(); i++) {
data.setCell(i, data.getNumberOfColumns() - 1, staticValue);
}
chart.draw(data);
}
}
&#13;
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button onclick="addStatic();">Add Static Column</button>
<== click this button to add a column with a static value in it
<div id="chart_div"></div>
&#13;