0

我正在尝试使用 JQGrid 创建本地表,在我更改数组之前一切正常,这是工作代码:

HTML 代码:

<div id=main style="width: 350px; height:200px;background-color:orange;">
<table id="grid"></table>
</div>

JS代码

$(document).ready(
    function()
    {        
        jQuery("#grid").jqGrid({
         datatype: 'local',
         colNames:["User Name","Meet","Time"],
         height:"100%",
         autowidth: true,
         colModel :[
                    {name:"name",index:"name"},
                    {name:"to_meet",index:"to_meet"},
                    {name:"time",index:"time"}
                    ],
                    gridview: true,
                    viewrecords: true    });

    });

var mydata = [
              {name:"test",to_meet:"111",time:"0500"},
              {name:"test2",to_meet:"112",time:"0530"},
              {name:"test3",to_meet:"113",time:"0600"},
              {name:"test4",to_meet:"114",time:"0630"},
              {name:"test5",to_meet:"115",time:"0700"},
              {name:"test6",to_meet:"116",time:"0730"},
              {name:"test7",to_meet:"117",time:"0800"},
              {name:"test8",to_meet:"118",time:"0830"},
              {name:"test9",to_meet:"119",time:"0900"},
              {name:"test10",to_meet:"120",time:"0930"},
              {name:"test11",to_meet:"121",time:"1000"},
              {name:"test12",to_meet:"122",time:"1030"},
              {name:"test13",to_meet:"123",time:"1100"},
              {name:"test14",to_meet:"124",time:"1130"},
              {name:"test15",to_meet:"125",time:"1200"},
              {name:"test16",to_meet:"126",time:"1230"}
    ];
    console.log(mydata.length)
    for(var i=0; i<mydata.length;i++)
{

  alert(mydata);
        jQuery("#grid").jqGrid('addRowData',i+1,mydata[i]); ;

}

你也可以从这里运行它:http: //jsfiddle.net/bYQn6/2/

现在,当我将 Obj 数组更改为:

$.each(myarray, function(i, val){
gridi.push('{name:"' + val.Name + '",to_meet:"' + val.meet + '",time:"' + val.time + '"}');
    });

var mydata = [gridi.toString()];

打印这个“mydata”看起来和上面的“mydata”一模一样,但它不起作用:(

我究竟做错了什么??

谢谢!!!

4

2 回答 2

0

你为什么要创建字符串并推入gridi?

您可以创建新对象,例如:

$.each(myarray, function(i, val){  
    gridi.push({'name': val.name, 'to_meet': val.meet, 'time':val.time});  
}  
});
于 2012-10-22T07:08:16.800 回答
0

将一个数组转换为另一个数组的正确方法是使用$.map

var mydata = $.map(myarray, function(val) {
    return {
        name: val.Name,
        to_meet: val.meet,
        time: val.time
    };
});

回调函数依次被赋予原始数组的每个元素,并将函数的返回值累加到一个新的数组中。

于 2012-10-22T07:12:31.790 回答