我试图转换这个HTML表:
码:
<table id="students" border="1"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Grade</th> </tr> </thead> <tbody> <tr class="student"> <td>Oscar</td> <td>23</td> <td>16.5</td> </tr> <tr class="student"> <td>Antonio</td> <td>32</td> <td>14</td> </tr> <tr class="student"> <td>Jessica</td> <td>21</td> <td>19</td> </tr> </tbody> </table>
使用jQuery进入javascript对象:
var tbl = $('table#students tr').map(function() { return $(this).find('td').map(function() { return $(this).text(); }).get(); }).get();
["Oscar","23","16.5","Antonio","32","14","Jessica","21","19"]
一切都很好,但是如果我想要数组中的javascript对象具有以下结构,该怎么办?
[{id:1,name: "Oscar",age: 23,grade: 16.5},{id:2,name: "Antonio",age: 32,grade: 14},{id:3,name: "Jessica",age: 21,grade: 19}]
只是为了更具体...
> id是从tr获得的
>从每行获得姓名,年龄和成绩值
我做了这个jsfiddle来测试:
http://jsfiddle.net/oscarj24/ptVDm/
谢谢
解决方法
var tbl = $('#students tr:has(td)').map(function(i,v) { var $td = $('td',this); return { id: ++i,name: $td.eq(0).text(),age: $td.eq(1).text(),grade: $td.eq(2).text() } }).get();