我正在努力执行以下操作:
我有张桌子:
<table id="saleDetails" class="table table-hover table-condensed">
<thead>
<tr>
<th>Code </th>
<th>Description </th>
<th>Price </th>
<th>Quantity </th>
</tr>
</thead>
<tbody>
<tr>
<th> 001 </th>
<th> One description </th>
<th> 30.5 </th>
<th> <input type="number"></input> </th>
</tr>
<tr>
<th> 002 </th>
<th> Some description </th>
<th> 120 </th>
<th> <input type="number"></input> </th>
</tr>
<tr>
<th> 003 </th>
<th> Other description </th>
<th> 300.5 </th>
<th> <input type="number"></input> </th>
</tr>
</tbody>
</table>我要做的是得到unitPrice,然后乘以数量输入值,得到每一行的小计。
在第3栏中,我得到了每个单元格的unitPrice和这个句子:
$('#saleDetails tr td:nth-child(3)').each(function () {
console.log( $(this).text() );
});但是我想执行unitPrice * quantity操作(quantity是一个输入组件),我不知道如何同时获得表上的每个迭代的unitPrice和quantity (我不确定这是否可能)。
欢迎任何帮助。
谢谢。
发布于 2017-03-19 18:09:38
你可以这样做:
$('#saleDetails tr').each(function () {
var price = $(this).find("td:nth-child(3)").text()
var quantity = $(this).find("td:nth-child(4) input").val()
console.log( quantity + " " + price);
});发布于 2017-03-19 18:06:59
可以使用DOM遍历方法以input为目标。使用.closest()遍历TR元素使用.find()定位input
$('#saleDetails tr td:nth-child(3)').each(function () {
var quantity = $(this).closest('tr').find('input').val();
console.log( $(this).text(), quantity );
});
$('#saleDetails tr td:nth-child(3)').each(function() {
var quantity = $(this).closest('tr').find('input').val();
console.log($(this).text().trim(), quantity);
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="saleDetails" class="table table-hover table-condensed">
<thead>
<tr>
<th>Code </th>
<th>Description </th>
<th>Price </th>
<th>Quantity </th>
</tr>
</thead>
<tbody>
<tr>
<td> 001 </td>
<td> One description </td>
<td> 30.5 </td>
<td> <input type="number" value="5" /></d>
</tr>
</tbody>
</table>
有多种方法,您也可以使用
var quantity = $(this).closest('td').next().find('input').val();发布于 2017-03-19 18:35:37
使用类选择器;小提琴来尝试这段代码
html:
<table id="saleDetails" class="table table-hover table-condensed">
<thead>
<tr>
<th>Code </th>
<th>Description </th>
<th>Price </th>
<th>Quantity </th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td> 001 </td>
<td> One description </td>
<td class="unitprice"> 30.5 </td>
<td> <input type="number" class="quantity" /> </td>
<td class="total"></td>
</tr>
<tr>
<td> 002 </td>
<td> Some description </td>
<td class="unitprice"> 120 </td>
<td> <input type="number" class="quantity" /> </td>
<td class="total"></td>
</tr>
</tbody>
</table>和js:
$('#saleDetails tr').on("change", ".quantity", function (event) {
var $row = $(event.delegateTarget);
var price = $row.find(".unitprice").text();
var quantity = $row.find(".quantity").val();
var total = price*quantity;
$row.find(".total").text(total);
});https://stackoverflow.com/questions/42890169
复制相似问题