当我尝试运行页面时,它在for循环中给出了一个错误“expected:”

时间:2013-01-06 15:27:14

标签: javascript

我使用谷歌可视化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>

1 个答案:

答案 0 :(得分: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);