【发布时间】:2013-12-31 10:01:51
【问题描述】:
我需要从表中获取数据并将其存储在数组中。表格的每一行都应该是数组中的一个新数组。基本上html看起来是这样的:
<table id="contactlisttable">
<tr>
<th>Name</th>
<th>Title</th>
<th>Phone</th>
</tr>
<tr>
<td class="contactlist contactlistlastfirst">Joey</td>
<td class="contactlist contactlisttitle">webdesigner</td>
<td class="contactlist contactlistphone">5555555</td>
</tr>
<tr>
<td class="contactlist contactlistlastfirst">Anthony</td>
<td class="contactlist contactlisttitle">webdesigner</td>
<td class="contactlist contactlistphone">5555555</td>
</tr>
</table>
等等……
这是我的代码
jQuery(document).ready(function(){
$(function(){
var $table = $("#contactlisttable"),
$headerCells = $table.find("tr th"),
$myrows = $table.find("tr"); // Changed this to loop through rows
var headers = [],
rows = [];
$headerCells.each(function() {
headers[headers.length] = $(this).text();
});
$myrows.each(function() {
$mycells = $myrows.find( "td.contactlist" ); // loop through cells of each row
cells = []
$mycells.each(function() {
cells.push($(this).text());
});
if ( cells.length > 0 ) {
rows.push(cells);
}
});
console.log(headers);
console.log(rows);
});
});
我当前的代码输出了
[["Waddell, Joey", "webdesigner", "", 15 more...], ["Waddell, Joey", "webdesigner", "", 15 more...],
期望的输出是:
["Name","Title","Phone"]
[["Joey","webdesigner","555555"]
["Anthony","webdesigner","555555"]]
【问题讨论】:
-
这是我的代码jsfiddle.net/joeylobo/m4dW6的工作示例
标签: javascript arrays