-1

我使用谷歌可视化 api!我知道所有 Google 可视化构造都接受 Javascript 对象 google.visualization.DataTable 的实例,该实例可以通过以下两种方式之一进行实例化。

所以我使用第二种方式,在这种方式中,我的数据表是用某种结构的 JSON 构造并使用特定属性的。问题是如您所见,我想使用 for 循环添加特定数量的行,当我尝试这样做时,它给了我上面提到的错误

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>
          Google Visualization API Sample
        </title>
        <script type="text/javascript" src="http://www.google.com/jsapi"></script>
        <script type="text/javascript">
          google.load('visualization', '1', {packages: ['table']});
        </script>
        <script>

        function drawVisualization()
        {
         var data = new google.visualization.DataTable
         (
           {
           cols: [
           {id: 'task',  label: 'Task',          type: 'string'},
           {id: 'hours', label: 'Hours per Day', type: 'number'},
            {id: 'E',   label: 'Action',          type:  'string'}
                  ],
                  for (i=0;i<3;i++) 
                  {
                    rows: [ 
                    {c:[{v: 'Work'},     {v: 5},     {v: '<input type="button" value="my button" onclick="alert(\'I was clicked!\');"/>'}]},
                    {c:[{v: 'Eat'},      {v: 2}]}
                           ]                     
                   }
             }         

         );



        visualization = new google.visualization.Table(document.getElementById('table'));
        visualization.draw(data, null);
        }
      google.setOnLoadCallback(drawVisualization);
        </script>
        </head>
        <body>
        <div id="table"></div>
        </body>
        </html>
4

1 回答 1

1

您的语法无效。您需要逐步构建对象,首先是静态部分,然后使用 for 循环添加其余部分:

var rawData = {
    cols: [
        {id: 'task',  label: 'Task',          type: 'string'},
        {id: 'hours', label: 'Hours per Day', type: 'number'},
        {id: 'E',     label: 'Action',        type:  'string'}
    ],
    rows: []
};

for (var i = 0; i < 3; i++)  {
    rawData.rows.push({
        c:[{v: 'Work'}, {v: 5}, {v: '<input type="button" value="my button" onclick="alert(\'I was clicked!\');"/>'}]
    });
    rawData.rows.push({
        c:[{v: 'Eat'}, {v: 2}, {v: ''}]
    });
}

var data = new google.visualization.DataTable(rawData);
于 2013-01-06T16:01:12.293 回答