如何通过closest类实现动态表格每行单价与数量的乘积计算?
解决动态表格每行单独计算总价的问题
核心问题大概率是你用了重复的ID选择器,或者没正确定位当前操作行的元素。以下是具体修改方案:
1. 调整HTML结构(避免重复ID)
把每行输入框的ID改为类名——动态添加的行如果用相同ID会导致DOM选择器失效:
<table id="priceTable"> <thead> <tr> <th>单价</th> <th>数量</th> <th>总价</th> </tr> </thead> <tbody> <!-- 初始行 --> <tr> <td><input type="number" class="p_price" value="0"></td> <td><input type="number" class="qty" value="0"></td> <td><input type="number" class="t_price" readonly></td> </tr> </tbody> </table> <button id="addRowBtn">添加新行</button>
2. 用事件委托处理动态行的计算
不需要给每一行单独绑定事件,直接监听表格的input事件,通过事件源定位当前行后计算:
const table = document.getElementById('priceTable'); const addBtn = document.getElementById('addRowBtn'); // 添加新行逻辑 addBtn.addEventListener('click', () => { const tbody = table.querySelector('tbody'); const newRow = document.createElement('tr'); newRow.innerHTML = ` <td><input type="number" class="p_price" value="0"></td> <td><input type="number" class="qty" value="0"></td> <td><input type="number" class="t_price" readonly></td> `; tbody.appendChild(newRow); }); // 事件委托实现每行单独计算 table.addEventListener('input', (e) => { // 监听数量输入变化 if (e.target.classList.contains('qty')) { const currentRow = e.target.closest('tr'); const price = parseFloat(currentRow.querySelector('.p_price').value) || 0; const qty = parseFloat(e.target.value) || 0; currentRow.querySelector('.t_price').value = (price * qty).toFixed(2); } // 同时监听单价变化,同步更新总价 if (e.target.classList.contains('p_price')) { const currentRow = e.target.closest('tr'); const price = parseFloat(e.target.value) || 0; const qty = parseFloat(currentRow.querySelector('.qty').value) || 0; currentRow.querySelector('.t_price').value = (price * qty).toFixed(2); } });
关键修改说明
- 类名替代ID:避免动态行的ID重复问题,确保DOM选择器能精准定位当前行的元素。
- 事件委托:利用事件冒泡特性,只给表格绑定一次事件,新增的行自动继承事件监听,无需重复绑定。
- 定位当前行:通过
e.target.closest('tr')锁定操作行,确保计算只针对当前行的单价和数量,不会干扰其他行。
内容的提问来源于stack exchange,提问作者Farlar
相关产品推荐
相关产品推荐

