You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

小型Todo应用总价求和异常求助:无法累加Li数值至H2

Todo应用总价求和问题排查与修复

问题描述

开发小型Todo应用时,无法获取每个新增Li元素的价格值并累加输出到H2标签中,始终无法得到正确的总价。

用户原代码

const form = document.querySelector("form")
const nameInput = document.querySelector("#name-input")
const priceInput = document.querySelector("#price-input")
const button = document.querySelector("button")
const nameUl = document.querySelector("#item-name")
const priceUl = document.querySelector("#item-price")
const h2 = document.querySelector("h2")

const nameLi = document.createElement("li")
const priceLi = document.createElement("li")


form.addEventListener("submit", function (e) {
    e.preventDefault()

    let nameVal = nameInput.value
    let priceVal = priceInput.value

    const nameLi = document.createElement("li")
    const priceLi = document.createElement("li")


    nameUl.appendChild(nameLi)
    nameLi.innerHTML = nameInput.value

    priceUl.appendChild(priceLi)
    priceLi.textContent = `${priceInput.value}`

    showTotals()
})


//TRYING TO ADD TOGETHER ALL THE PRICE VALUES AND THEN PUT IT TO MY H2//
function showTotals() {
    const priceList = document.querySelectorAll("li")

    for (let priceLists of priceList) {
        const total = []
        total.push(parseFloat(priceLists.textContent));
        const totalMoney = total.reduce(function (total, item) {
            total += item;
            return total;
        }, 0);

        const finalMoney = totalMoney.toFixed(2);
        h2.textContent = finalMoney;
    }
}

问题根源

  1. 选择器范围错误:document.querySelectorAll("li")会选中所有列表项,包括左侧的任务名称Li,这些项的文本无法转换为数字,导致求和逻辑混乱。
  2. 数组重置导致无法累加:在for...of循环内部每次都新建total数组,每次仅存入当前单个价格,reduce后只能得到当前项的价格,无法累积所有值。
  3. 循环内重复更新DOM:每次循环都修改H2的内容,最终只会显示最后一个Li的价格,而非所有价格的总和。

修复后的代码

const form = document.querySelector("form")
const nameInput = document.querySelector("#name-input")
const priceInput = document.querySelector("#price-input")
const nameUl = document.querySelector("#item-name")
const priceUl = document.querySelector("#item-price")
const h2 = document.querySelector("h2")

form.addEventListener("submit", function (e) {
    e.preventDefault()

    const nameLi = document.createElement("li")
    const priceLi = document.createElement("li")

    nameLi.textContent = nameInput.value
    priceLi.textContent = priceInput.value

    nameUl.appendChild(nameLi)
    priceUl.appendChild(priceLi)

    // 清空输入框,提升操作体验
    nameInput.value = ""
    priceInput.value = ""

    showTotals()
})

function showTotals() {
    // 仅选择价格列表下的Li元素,避免混入任务名称
    const priceItems = document.querySelectorAll("#item-price li")
    let total = 0

    // 遍历所有价格项,累加有效数字
    priceItems.forEach(item => {
        const price = parseFloat(item.textContent)
        if (!isNaN(price)) {
            total += price
        }
    })

    // 格式化为两位小数后更新H2
    h2.textContent = total.toFixed(2)
}

修复要点

  • 精准选择目标元素:使用#item-price li定位价格列表项,排除任务名称项的干扰。
  • 正确的累加逻辑:在循环外部初始化总和变量,遍历过程中逐步累加有效价格值。
  • 合法性校验:通过isNaN判断价格是否为有效数字,避免非数字内容导致计算错误。
  • 优化用户体验:提交表单后清空输入框,方便用户继续添加新任务。

内容的提问来源于stack exchange,提问作者Chase Hudson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 14:10:39