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

如何使用JavaScript获取表格行内指定class的span元素

核心错误点

document.getElementById()返回值是单个匹配ID的DOM元素,并非类数组集合,直接对单个元素执行Array.from()无法得到可遍历的行列表,这是筛选逻辑失效的根本原因。
另外HTML规范要求页面内ID全局唯一,如果你存在多个ID带electric-totals-前缀的行元素,本身就不符合规范,建议给这类行统一添加相同类名(比如electric-total-row),通过类选择器获取集合。


修复方案

原生JS实现(无需jQuery)

function fieldTotals() {
    const calculatedFields = document.getElementsByClassName("field-total");
    Array.from(calculatedFields).forEach((el) => {
        const fieldId = el.id;
        const currentRow = document.getElementById(`electric-totals-${fieldId}`);
        if (!currentRow) return; // 匹配不到对应元素直接跳过,避免抛出错误

        let totalSum = 0;
        // 在当前行范围内查找所有带total-span类的元素
        const spanList = currentRow.querySelectorAll(".total-span");
        spanList.forEach(span => {
            // 提取整数值,处理空白、非数字异常场景
            const numVal = parseInt(span.innerHTML.trim(), 10);
            if (!isNaN(numVal)) {
                totalSum += numVal;
            }
        });

        // 此处totalSum即为当前行的求和结果,可按需做后续赋值、渲染操作
        console.log(totalSum);
    });
}

jQuery 实现

如果你项目中已经引入jQuery,可以用更简洁的写法实现:

function fieldTotals() {
    $(".field-total").each(function() {
        const fieldId = this.id;
        const $currentRow = $(`#electric-totals-${fieldId}`);
        let totalSum = 0;

        $currentRow.find(".total-span").each(function() {
            const numVal = parseInt($(this).html().trim(), 10);
            if (!isNaN(numVal)) {
                totalSum += numVal;
            }
        });

        console.log(totalSum);
    });
}

注意事项
  • 调用parseInt时必须传入第二个参数10指定十进制解析,避免开头带0的字符串被误解析为八进制值
  • 取值前对innerHTML做trim()处理,清除首尾不可见的空白字符,防止数字解析失败
  • 增加非数字判断逻辑,避免span内容为空、包含非数字字符时导致整个计算逻辑报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 16:15:37