我有这样的表
<table>
<thead>
<tr>
<td> no. </td>
<td> Item </td>
<td> value </td>
</tr>
</thead>
<tbody>
<tr>
<td> 1 </td>
<td> A </td>
<td> 50 </td>
</tr>
<tr>
<td> 2 </td>
<td> B </td>
<td> 25 </td>
</tr>
<tr>
<td> 3 </td>
<td> C </td>
<td> 150 </td>
</tr>
</tbody>
</table>
我的问题是如何将我的表内容压缩到像这样的数组
[['1';'A';'50'];['2';'B';'25'],['3';'C';'150']]
在javascript上,我需要发送到ajax。如果你问我在哪里,我还没有做什么,因为我仍然坚持这个问题。
答案 0 :(得分:1)
使用$.each
循环
var result = [];
$('table tbody tr').each(function() {
var tmp = [];
$(this).children().each(function() {
tmp.push($.trim($(this).text())); // cut spaces
})
result.push(tmp);
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<td> no. </td>
<td> Item </td>
<td> value </td>
</tr>
</thead>
<tbody>
<tr>
<td> 1 </td>
<td> A </td>
<td> 50 </td>
</tr>
<tr>
<td> 2 </td>
<td> B </td>
<td> 25 </td>
</tr>
<tr>
<td> 3 </td>
<td> C </td>
<td> 150 </td>
</tr>
</tbody>
</table>
答案 1 :(得分:0)
你可以像下面这样做,
var result = $("table tbody tr").get().map(function(itm) {
return $("td", itm).get().map(function(itm){
return itm.textContent;
})
});
console.log(result);
答案 2 :(得分:0)
很简单,你甚至不需要jQuery:
// A utility function so that the code is clearer
function mapSelector(parent, selector, fun){
return [].map.call(parent.querySelectorAll(selector), fun);
}
// the table, you might want to select a specific one
var tbl = document.querySelector("tbody");
// the operation
var rows = mapSelector(tbl, "tr", tr => mapSelector(tr, "td", td => td.textContent));
// just logging
document.querySelector("#result").innerHTML = JSON.stringify(rows);
&#13;
<pre id=result></pre>
<table>
<thead>
<tr>
<td> no. </td>
<td> Item </td>
<td> value </td>
</tr>
</thead>
<tbody>
<tr>
<td> 1 </td>
<td> A </td>
<td> 50 </td>
</tr>
<tr>
<td> 2 </td>
<td> B </td>
<td> 25 </td>
</tr>
<tr>
<td> 3 </td>
<td> C </td>
<td> 150 </td>
</tr>
</tbody>
</table>
&#13;
答案 3 :(得分:0)
使用纯JavaScript可以:
var trs = document.getElementsByTagName('table')[0].getElementsByTagName('tr'),
resultArr = [].map.call(trs, tr => [].map.call(tr.getElementsByTagName('td'), td => td.innerHTML.trim()));
console.log(resultArr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<table><thead><tr><td> no. </td><td> Item </td><td> value </td></tr></thead><tbody><tr><td> 1 </td><td> A </td><td> 50 </td></tr><tr><td> 2 </td><td> B </td><td> 25 </td></tr><tr><td> 3 </td><td> C </td><td> 150 </td></tr></tbody></table>
答案 4 :(得分:-1)
只需遍历每一行中的所有<td>
并将它们推入临时数组,一旦行完成,将该数组移动到主数组。执行相同操作直到涵盖所有<td>
jQuery代码:
$(function() {
var colCount = $('thead td').length;
var res = [];
var tempArr = [];
$('tbody tr td').each(function(index) {
tempArr.push($(this).text());
if ((index + 1) % colCount === 0) {
res.push(tempArr);
tempArr = [];
}
});
alert(res);
});