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

为什么我的JS克隆代码会打乱整个HTML表格结构?

问题原因分析
  • 原JS逻辑错误:当前代码尝试克隆按钮的父级的父级节点,该节点并非要复制的表格行,所以新增内容不符合预期
  • 缺少新增次数计数逻辑,无法限制最多新增10次
  • 原始HTML的tbody下缺少<tr>包裹td元素,结构不规范
  • 克隆后元素id重复,会导致label关联和表单提交异常
修复后完整代码

HTML代码

<table id="tbl" class="table-bordered table-dark">
  <thead>
    <tr>
      <th scope="colgroup">开始时间</th>
      <th scope="colgroup">结束时间</th>
    </tr>
  </thead>
  <tbody>
    <!-- 新增tr包裹原有td -->
    <tr class="data-row">
      <td style="vertical-align: top;">
        <label>数据:</label>
        <input type="date" name="data-roz[]"> <br>
        <label>时间:</label>
        <input type="time" name="godz-roz[]">
      </td>
      <td style="vertical-align: top;">
        <label>数据:</label>
        <input type="date" name="data-zakon[]"> <br>
        <label>时间:</label>
        <input type="time" name="godz-zakon[]">
      </td>
    </tr>
  </tbody>
</table>
<input type="button" class="btn btn-primary" value="+" onclick="addField();"/>

JS代码

// 初始已有1行,最多新增10行总上限为11行
let rowCount = 1;
const MAX_ROWS = 11;

function addField() {
  if(rowCount >= MAX_ROWS) {
    alert("最多只能新增10行");
    return;
  }
  // 克隆第一行数据行
  const firstRow = document.querySelector('.data-row');
  const newRow = firstRow.cloneNode(true);
  
  // 清空新行的输入值
  newRow.querySelectorAll('input').forEach(input => input.value = '');
  
  // 追加到表格
  document.querySelector('#tbl tbody').appendChild(newRow);
  rowCount++;
}
修改说明
  • 给原有行加了data-row类名,方便准确获取要克隆的目标行
  • 新增计数逻辑,严格限制最多新增10行
  • 移除了重复的id属性,把表单控件name改成数组形式,方便后端批量接收数据
  • 克隆后自动清空新行的输入值,避免复制原有行的已填内容
  • 修正了HTML结构的tr缺失问题,确保表格渲染正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:06:03