如何从表行和列中获取所有值到数组
field1 field2 field3
1 aaa aaa
2 bbb bbb
3 ccc ccc
4 ddd ddd
我想从表行到数组中获取值,如下所示:
array1=[["1","aaa","aaa"],["2","bbb","bbb"],["3","ccc","ccc"],["4","ddd","ddd"]];
我的html
<table>
<thead>
<tr>
<th>field1</th>
<th>field2</th>
<th>field3</th>
</tr>
</thead>
<tr>
<td>1</td>
<td>aaa</td>
<td>aaa</td>
</tr>
<tr>
<td>2</td>
<td>bbb</td>
<td>bbb</td>
</tr>
<tr>
<td>3</td>
<td>ccc</td>
<td>ccc</td>
</tr>
<tr>
<td>4</td>
<td>ddd</td>
<td>ddd</td>
</tr>
</table>
有什么解决办法吗?谢谢
答案 0 :(得分:3)
您可以尝试:
function get(){
var table = $('table');
var data = [];
table.find('tr').each(function (i, el) {
// no thead
if( i != 0){
var $tds = $(this).find('td');
var row = [];
$tds.each(function (i, el){
row.push($(this).text());
});
data.push(row);
}
});
return data;
}
console.log(get());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>field1</th>
<th>field2</th>
<th>field3</th>
<th>field4</th>
</tr>
</thead>
<tr>
<td>1</td>
<td>aaa</td>
<td>aaa</td>
</tr>
<tr>
<td>2</td>
<td>bbb</td>
<td>bbb</td>
</tr>
<tr>
<td>3</td>
<td>ccc</td>
<td>ccc</td>
</tr>
<tr>
<td>4</td>
<td>ddd</td>
<td>ddd</td>
</tr>
</table>