2016-06-19 13 views
0

我有一個基於一個JSON表的包裝一個谷歌的圖表(作爲數據源)如何「靜態」列添加到基於一個JSON表一個谷歌的圖表

var data = new google.visualization.DataTable(<?=$jsonTableA>); 

如何能我點擊一個按鈕添加一個靜態值的列?

我的意思是,我將有一個變量(讓我們假設該變量的值是4),如果JSON表有5行,那麼NEW數據中的所有5行將具有「4」列...如果JSON表格有20行,NEW數據中的所有20行將在該列中具有「4」。

回答

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); 
 
    } 
 

 
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> 
 
<button onclick="addStatic();">Add Static Column</button> 
 
&lt;== click this button to add a column with a static value in it 
 
<div id="chart_div"></div>

+0

我們再次見面:)謝謝保羅。非常感謝你。 –

相關問題