Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

javascript - Draw multiple Google charts in for loop

I am trying to draw multiple Google charts in a for loop, but can't seem to make it work. I have seen some similar questions being asked, but only with PHP. Anyone who can help? This is what I have tried so far https://jsfiddle.net/8nfbz1v1/

        <ul id="draw-charts"></ul>

  google.charts.load('current', {'packages':['corechart']});

for(var i = 0; i>6; i+){
var charts = "";
    google.charts.setOnLoadCallback(drawChart);

  function drawCharts() {

  charts += '<td><div id="chart_div' + i +'" style="border: 1px solid #ccc"></div></td>';
  $("#draw-charts").html(charts);

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Topping');
    data.addColumn('number', 'Slices');
    data.addRows([
      ['Mushrooms', 1],
      ['Onions', 1],
      ['Olives', 2],
      ['Zucchini', 2],
      ['Pepperoni', 1]
    ]);

    var options = {title:'How Much Pizza Sarah Ate Last Night',
                   width:400,
                   height:300};

    // Instantiate and draw the chart for Sarah's pizza.
    var chart = new google.visualization.PieChart(document.getElementById('chart_div' + i));
    chart.draw(data, options);
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

setOnLoadCallback should only be called once per page load

once it fires, you can draw as many charts as needed

you can also include the callback in the load statement

see following working snippet...

google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Topping');
    data.addColumn('number', 'Slices');
    data.addRows([
      ['Mushrooms', 1],
      ['Onions', 1],
      ['Olives', 2],
      ['Zucchini', 2],
      ['Pepperoni', 1]
    ]);
    var options = {
      title:'How Much Pizza Sarah Ate Last Night',
      width:400,
      height:300
    };

    for (var i = 0; i < 6; i++) {
      var container = document.getElementById('draw-charts').appendChild(document.createElement('div'));
      var chart = new google.visualization.PieChart(container);
      chart.draw(data, options);
    }
  },
  packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<ul id="draw-charts"></ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...