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

使用JavaScript为表格td设置data-title属性出现undefined如何修复

问题原因
  • 表头只有3个th元素,所以你收集到的title数组长度固定为3
  • 表格tbody内共有6个td元素(2行×3列),遍历所有checkout-info元素时,索引大于等于3的位置,title数组不存在对应下标的值,就会返回undefined
修复方案

直接用取余运算让索引循环匹配表头数组长度即可,不管后续加多少行数据都能自动对应对应列的标题:

let title = [];
document.querySelectorAll('.checkout-title').forEach(el => {
    title.push(el.innerHTML);
});

document.querySelectorAll('.checkout-info').forEach((el, index) => {
    el.setAttribute('data-title', title[index % title.length]);
});
更稳妥的层级遍历方案(适配列合并等特殊场景)

如果后续表格可能有列合并的需求,推荐用按行→按列的层级遍历逻辑,可读性和兼容性更强:

const titles = Array.from(document.querySelectorAll('.checkout-title')).map(el => el.textContent);
const tableRows = document.querySelectorAll('.checkout-list tbody tr');

tableRows.forEach(row => {
  const cells = row.querySelectorAll('.checkout-info');
  cells.forEach((cell, colIndex) => {
    cell.setAttribute('data-title', titles[colIndex]);
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:45:00