点击移除按钮时updatevalue函数不生效、总和未更新问题求助
问题根因
- 总和更新逻辑仅绑定在输入框的
oninput事件中,remove_item函数手动修改数值为0时没有主动触发总和重新计算 - 原有代码中使用
document.querySelectorAll(".int-input")是全局选中所有计数单元格,会导致不同div的总和互相干扰 - 频繁使用
nextSibling可能拿到空白文本节点,DOM结构稍有变动就会定位错误
修复代码
1. 新增公共总和计算函数
// 计算当前容器内的总和 function calcTotal(container) { let total = 0; container.querySelectorAll(".int-input").forEach(item => { total += parseInt(item.innerHTML) || 0; }); container.querySelector(".total").innerHTML = total; }
2. 优化updatevalue函数
function updatevalue(item, value, data) { const countTd = item.parentNode.nextElementSibling; const rootDiv = item.closest('div'); const onupdate = value ? data * Number(value) : 0; countTd.innerHTML = onupdate; calcTotal(rootDiv); }
3. 修改remove_item函数,新增总和计算调用
function remove_item(item, prev) { const inputEle = item.parentNode.nextElementSibling.nextElementSibling.firstChild; const countTd = item.parentNode.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling; inputEle.disabled = true; inputEle.value = '0'; countTd.innerHTML = '0'; item.parentNode.style.display = "none"; prev.style.display = "block"; // 移除后重新计算当前区域总和 calcTotal(item.closest('div')); }
可选优化:优化add_item的节点定位逻辑,提升稳定性
function add_item(item, next) { const inputEle = item.parentNode.nextElementSibling.nextElementSibling.firstChild; item.parentNode.style.display = "none"; next.style.display = "block"; inputEle.value = ''; inputEle.disabled = false; }
内容的提问来源于stack exchange,提问作者Jashan Dhiman
相关产品推荐
相关产品推荐

