我一直有这个问题,我不能完全通过其他给定的解决方案来解决。
我正在尝试获取表中每一行的特定值。这个问题来自一个相当没有格式化的表,所以我必须根据它们的索引或位置来获取单元格的值。
这是有问题的表格:
<table width="100%">
<thead>
<tr>
<td>Item Description</td>
<td>Colour</td>
<td>Size</td>
<td class="text-right">Price</td>
<td class="text-right">Qty</td>
<td class="text-right">Total</td>
</tr>
</thead>
<tbody>
<tr id="row_24551">
<td width="40%">Item 1</td>
<td>Ivory</td>
<td>10</td>
<td class="text-right">$ 19.00</td>
<td class="text-right">1</td>
<td class="text-right">$ 19.00</td>
</tr>
<tr id="row_24550">
<td width="40%">Item 2</td>
<td>Grey Marle</td>
<td>10</td>
<td class="text-right">$ 18.95</td>
<td class="text-right">1</td>
<td class="text-right">$ 18.95</td>
</tr>
</tbody>
</table>
我一直使用以下命令获取行值:
作为所需信息的var table = $('tr[id^="row"]')
位于具有ID的行中。
可以输出每个单元格的内容
var table = $('tr[id^="row"]');
table.each(function(){
console.log('row');
$.each(this.cells, function(){
console.log($(this).text());
});
});
我被卡住的地方是,我只想要单元格0,2,4,5,而且我不确定如何通过.each函数进行选择。
For循环对我来说更有意义,但我还不能通过行获得单元的迭代:
var table = $('tr[id^="row"]');
for(i = 0; i < table.length; i++) {
console.log("row");
}
我也试过这个
var table = $('tr[id^="row"]');
for(var i = 0, row; row = table[i]; i++) {
console.log("row");
for (var j = 0, col; col = row[j]; j++) {
console.log("cell");
}
}
但是单元格的值似乎不能通过。
最终希望将所需的每个单元格值( 0,2,4,5 )推送到一个product数组中,该数组将映射{name,size,quantity,price}。不过,如果能帮上忙,我会非常感激的!
发布于 2018-02-05 19:37:02
您可以像这样使用单元格的索引:
var table = $('tr[id^="row"]')
var tabCells = {0: "name", 2: "size", 4: "quantity", 5: "price"} //These are the names of the needed cells
var tabRows = []; //This will store the rows data
table.each(function(){
var tabRow = {}; //This will store the current row data
$.each(this.cells, function(index){
if($.inArray(index, [0,2,4,5]) > -1)
tabRow[tabCells[index]] = $(this).text();
//e.g: tabRow[tabCells[0]] => tabRow["name"]
})
tabRows.push(tabRow);
})
发布于 2018-02-05 19:37:22
试试cellIndex:
var table = $('tr[id^="row"]');
table.each(function() {
$.each(this.cells, function() {
if ([0, 2, 4, 5].indexOf(this.cellIndex) > -1) {
console.log($(this).text());
}
});
});
发布于 2018-02-05 19:45:53
这是一个仅使用JavaScript的解决方案。如果你需要支持老的浏览器,我可以重写它。
var rows = document.querySelectorAll('tr[id^="row"]');
//const rowArray = Array.from(rows);
var rowArray = Array.prototype.slice.call(rows);
var products = rowArray.reduce((sum, element) => {
var children = element.children;
var name = children[0].innerHTML;
var size = children[2].innerHTML;
var quantity = children[4].innerHTML;
var prize = children[5].innerHTML;
var newElement = {name: name, size: size, quantity: quantity, prize: prize};
sum.push(newElement);
return sum;
},[]);
console.log(products);
// [{name: "Item 1", size: "10", quantity: "1", prize: "$ 19.00"},
// {name: "Item 2", size: "10", quantity: "1", prize: "$ 18.95"}]
https://stackoverflow.com/questions/48621585
复制相似问题