[英]Get IDs of Multiple <td> in a <tr> with Javascript or JQuery
我的 html 中有以下內容:
<table id = 'manifest-table25' class="manifest-table2" width=100%>
<tbody width=100%>
<tr class="manifest-row">
<td width = 17.5%>{{form2.ProductCode}}</td>
<td width = 32.5%>{{form2.DescriptionOfGoods}}</td>
<td width = 12.5% class="quantity">{{form2.UnitQty}}</td>
<td width = 12.5%>{{form2.Type}}</td>
<td width = 12.5% oninput="calculate()">{{form2.Price}}</td>
<td width = 12.5%>{{form2.Amount}}</td>
</tr>
</tbody>
</table>
我有一個 function calculate()
調用 oninput 到 Price 字段,它將 UnitQty * Price 相乘並以 Amount 顯示結果。
<script>
function calculate() {
var UnitQty = document.getElementById('id_form-0-UnitQty').value;
var Price = document.getElementById('id_form-0-Price').value;
var LineTotal = UnitQty * Price;
$('#id_form-0-Amount').val(LineTotal);
}
</script>
這完美地工作,但被硬編碼以使用那些特定的 ID。 我的困境是用戶可以動態地將行添加到該表中,而這僅適用於一行。 因此,如果用戶再添加一行,顯然上述內容是硬編碼的,不適用於該新行。 為新行調用的 function 需要有效地看起來像這樣:
<script>
function calculate() {
var UnitQty = document.getElementById('id_form-1-UnitQty').value;
var Price = document.getElementById('id_form-1-Price').value;
var LineTotal = UnitQty * Price;
$('#id_form-1-Amount').val(LineTotal);
}
</script>
所以我需要一些方法來動態選擇替換 function 中的 ID,基於它實際上正在輸入。我完全堅持想一個方法,有人可以幫忙嗎?
我猜想{{...}}
在這些td
元素中創建input
元素。
最小的改變就是改變
oninput="calculate()"
至
oninput="calculate(this)"
它將觸發事件的元素傳遞到 function,然后在 function 中使用 DOM 導航:
function calculate(el) {
// Find the row containing this cell
var row = el.closest("tr");
// Get the quantity from the `input` in the `.quantity` cell in this row
var unitQty = row.querySelector('.quantity input').value;
// Get the price from the `input` in this cell (could use `e.target` instead)
var price = el.querySelector('input').value;
// Do the calculation, assign to the `input` in the `.amount` cell in this row
var lineTotal = unitQty * price;
row.querySelector(".amount input").value = lineTotal;
}
(注意:我已更新該代碼以遵循標准 JavaScript 變量命名約定。)
為了避免讓它變得非常脆弱,我在最后一個querySelector
調用的最終td
中添加了一個 class 。
或者,如果您更喜歡 jQuery:
function calculate(el) {
// Find the row containing this cell
var row = $(el).closest("tr");
// Get the quantity from the `input` in the `.quantity` cell in this row
var unitQty = row.find('.quantity input').val();
// Get the price from the `input` in this cell (could use `e.target` instead)
var price = $(el).find('input').val();
// Do the calculation, assign to the `input` in the `.amount` cell in this row
var lineTotal = unitQty * price;
row.find(".amount input").val(lineTotal);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.