使用Google Chart Api以编程方式更新购物车

时间:2013-11-12 12:09:23

标签: javascript jquery google-visualization

也许它重复但无法找到之前主题的解决方案。我想在我的多个图表中添加/删除一些数据。但我全局声明dataTable var并将其设置为onCallBack,没问题。但我希望在使用Ajax回调后添加/删除数据。

var testRows = [
    ['Test-A', 4, 3],
    ['Test-B', 1, 2],
    ['Test-C', 3, 4],
    ['Test-D', 2, 0],
    ['Test-E', 2, 5]
];
var testRow = ['Test-F', 8, 1];
var data = null;

google.load("visualization", "1", {
    packages: ["corechart", 'table']
});

google.setOnLoadCallback(function () {
    data = new google.visualization.DataTable();
    data.addColumn('string', 'Task');
    data.addColumn('number', 'Hours per Day');
    data.addColumn('number', 'How Sexy');
    data.addRows(testRows);
    drawChart('tablechart', 'div_id_1', testRow, null);
    drawChart('columnChart', 'div_id_2', null, null);
});

function drawChart(chartType, containerID, row, options) {
    data.addRow(row);
    var containerDiv = document.getElementById(containerID);
    var chart = false;
    if (chartType.toUpperCase() == 'BARCHART') {
        chart = new google.visualization.BarChart(containerDiv);
    } else if (chartType.toUpperCase() == 'COLUMNCHART') {
        chart = new google.visualization.ColumnChart(containerDiv);
    } else if (chartType.toUpperCase() == 'PIECHART') {
        chart = new google.visualization.PieChart(containerDiv);
    } else if (chartType.toUpperCase() == 'TABLECHART') {
        chart = new google.visualization.Table(containerDiv);
    }

    if (chart == false) {
        return false;
    }
    chart.draw(data, options);
}

drawChart('tablechart', 'div_id_1', ['abiz',5,2], null);
drawChart('columnChart', 'div_id_2', ['cabiz',5,2], null);

http://jsfiddle.net/eron/gD7KL/1/

1 个答案:

答案 0 :(得分:10)

您只需操纵DataTable,然后为每个表调用draw()即可。像这样:

var columnChart, tableChart;
document.getElementById('change-btn').onclick=function() {
    data.removeRow(0);
    data.insertRows(0, [['Test-A-changed', 14, 13]]);
    columnChart.draw(data);
    tableChart.draw(data);
}
上面的小提琴分叉以证明这一点 - >的 http://jsfiddle.net/Hw9U5/ 我也更改了drawChart - 函数以跟踪图表实例。