![](/img/trans.png)
[英]jQuery: select all `<td>` of a `<tr>` except a particular `<td>`
[英]Select all thead and tr has td except the last column
我编写此代码以获取表的所有值并插入带有索引名称的数组。
代码运行良好,但我想排除表格的最后一列。
var array = [];
var headers = [];
$('#idTable th').each(function(index, item)
{
headers[index] = $(item).html();
});
$('#idTable tr').has('td').each(function()
{
var arrayItem = {};
$('td', $(this)).each(function(index, item)
{
arrayItem[headers[index]] = $(item).html();
});
array.push(arrayItem);
});
我已经尝试过not(:last-child)
但最后一列仍然包括在内。
检查我的jsfiddle。 https://jsfiddle.net/del17/1yx3csrw/3/
这应该做你想要的:
var array = []; var headers = []; $('#idTable th:not(:last-child)').each(function() { headers.push($(this).text()) }) $('#idTable tbody tr').each(function() { var arrayItem = {}; $(this).find('td:not(:last-child)').each(function(i) { arrayItem[headers[i]] = $(this).text(); }) array.push(arrayItem); }); console.log(array) console.log(headers)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="idTable"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> </tr> </thead> <tbody> <tr> <td>a1</td> <td>b1</td> <td>c1</td> <td>d1</td> </tr> <tr> <td>a2</td> <td>b2</td> <td>c2</td> <td>d2</td> </tr> </tbody> </table>
我认为对于您想要做的事情,最好使用“文本”而不是“html”。
此外,如果您知道您遍历相同的顺序,请不要过多地使用索引。
如果您想像在这里所做的那样将元素添加到数组中,最好使用“push”。
这是小提琴: https://jsfiddle.net/p0qu5mc9/
var array = [];
var headers = [];
var columnlength = document.getElementById('idTable').rows[0].cells.length;
$('#idTable th').each(function(index, item)
{
if(columnlength-1 > index){
headers[index] = $(item).html();
}
});
$('#idTable tr').has('td').each(function()
{
var arrayItem = {};
$('td', $(this)).each(function(index, item)
{
if(columnlength-1 > index){
arrayItem[headers[index]] = $(item).html();
}
});
array.push(arrayItem);
});
alert(JSON.stringify(array));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.