为什么这些HTML表格's字段在加载时不计算?



我如何确保函数的第二部分运行,计算列并在每行结束时显示结果?

function sum_row_qty(el, poOrigin) {
let rowTotal = 0
if (el) {
let parent = el.closest("tr")
parent.querySelectorAll('.size_qty').forEach(function(e) {
rowTotal += parseFloat(e.value);
})
if (rowTotal) {
parent.querySelector('.qty').value = rowTotal;
}
} else {
document.querySelectorAll("#tableRows > tr > td:first-child input").forEach(sum_row_qty);
}
}
<table class="table table-hover table-vcenter" id="dtable">
<thead>
<tr>
<th style="width:4%; text-align: left">OS</th>
<th style="width:4%">XS</th>
<th style="width:4%">Total</th>
</tr>
</thead>
<tbody id="tableRows">
<tr>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="14" onchange="sum_row_qty(this);"></td>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="0" onchange="sum_row_qty(this)"></td>
<td><input type="number" min="0" class="qty" name="numberInputs" value="" readonly="true"></td>
</tr>
<tr>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="14" onchange="sum_row_qty(this);"></td>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="0" onchange="sum_row_qty(this);"></td>
<td><input type="number" min="0" class="qty" name="numberInputs" value="" readonly="true"></td>
</tr>
</tbody>
</table>

这是另一个平台上一位先生提出的答案:

function sumInputs(row) {
const inputsArr = [...row.querySelectorAll('.size_qty')];
return inputsArr.reduce((total, {
value
}) => total += parseFloat(value), 0);
}
function sum_row_qty(el) {
if (el) {
const currentRow = el.closest("tr");
currentRow.querySelector('.qty').value = sumInputs(currentRow);
}
}
tableRows.querySelectorAll('tr').forEach(row => {
row.querySelector('.qty').value = sumInputs(row);
});
<table class="table table-hover table-vcenter" id="dtable">
<thead>
<tr>
<th style="width:4%; text-align: left">OS</th>
<th style="width:4%">XS</th>
<th style="width:4%">Total</th>
</tr>
</thead>
<tbody id="tableRows">
<tr>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="14" onchange="sum_row_qty(this);"></td>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="0" onchange="sum_row_qty(this)"></td>
<td><input type="number" min="0" class="qty" name="numberInputs" value="" readonly="true"></td>
</tr>
<tr>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="14" onchange="sum_row_qty(this);"></td>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="0" onchange="sum_row_qty(this);"></td>
<td><input type="number" min="0" class="qty" name="numberInputs" value="" readonly="true"></td>
</tr>
</tbody>
</table>

最新更新