谷歌图表重绘onclick

时间:2015-06-04 09:56:49

标签: javascript jquery drop-down-menu charts google-visualization

我正在尝试制作一个图表,通过各种下拉菜单和日期选择器可以从中选择数据。我似乎无法找到一种方法来在点击事件中传递图表中的新数据。到目前为止,我已经开始工作了onClick,它绘制了一个全新的图表。但这似乎不适合我。

还有另外一种方法吗? HTML:

my_array[a]=0;myarray[b]=0; ...

JS:

<div id="piechart" style="width: 450px; height: 500px;"></div>
     <div class="date-selector-container">
       <div class="btn-group">
          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                        Jaar <span class="caret"></span>
           </button>
           <ul class="dropdown-menu" role="menu">
              <li><a class="2015-btn" href="#">2015</a></li>
              <li><a href="#">2014</a></li>
              <li><a href="#">2013</a></li>
           </ul>
</div>

1 个答案:

答案 0 :(得分:6)

将您的js更改为如下所示。

在drawChart函数之外创建图表变量,而不是在您已经拥有的图表的任何地方创建新图表。

此处的工作示例jsfiddle

google.load("visualization", "1", {packages:["corechart"], "callback": drawChart});
google.setOnLoadCallback(drawChart);

var chart;

function drawChart() {

    var data = google.visualization.arrayToDataTable([
        ['Task', 'Hours per Day'],
        ['Work',     1],
        ['Eat',      22],
        ['Commute',  32],
        ['Watch TV', 42],
        ['Sleep',    75]
    ]);

    var options = {

        chartArea: {width:'100%',height:'100%'},

        forceIFrame: 'false',

        is3D: 'true',

        pieSliceText: 'value',

        sliceVisibilityThreshold: 1/20, // Only > 5% will be shown.

        titlePosition: 'none'

    };


    chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
}


$(document).ready(function(){
//On button click, load new data
    $(".2015-btn").click(function() {

        var data = google.visualization.arrayToDataTable([
            ['Task', 'Hours per Day'],
            ['Work', 11],
            ['Eat', 2],
            ['Commute', 2],
            ['Watch TV', 2],
            ['Sleep', 7]
        ]);

        var options = {

            chartArea: { width: '100%', height: '100%' },

            forceIFrame: 'false',

            is3D: 'true',

            pieSliceText: 'value',

            sliceVisibilityThreshold: 1 / 20, // Only > 5% will be shown.

            titlePosition: 'none'

        };
        chart.draw(data, options);

    });
});