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

如何获取HTML克隆表单值并为克隆行设置唯一id

问题解答

1. 克隆后原有id属性是否会保留?

会。jQuery的clone()方法默认会完整复制目标元素的所有属性、子节点内容,id属性也会原样复制,所以你当前的写法执行克隆后,一定会出现多组id为start、end的输入框,属于不符合规范的id重复问题,会导致label点击关联失效、按id选择元素时取值混乱等问题。

2. 新增行设置唯一id的实现方案

可以维护一个自增计数器,每次克隆新行后,遍历行内的label和input元素,给id和对应的for属性加上当前计数器值作为后缀,保证全局唯一即可,修改后的代码如下:

修改后的JS代码

jQuery(function($) {
  var $button = $('#add-row'),
    $row = $('.period-row').clone(),
    // 新增计数器,记录当前行序号
    rowIndex = 1;

  $button.click(function() {
    // 克隆新行
    const $newRow = $row.clone();
    // 遍历修改行内的label和input属性
    $newRow.find('input').each(function() {
      const originId = $(this).attr('id');
      const newId = `${originId}_${rowIndex}`;
      $(this).attr('id', newId);
      // 找对应label,修改for属性
      $newRow.find(`label[for="${originId}"]`).attr('for', newId);
    })
    // 插入新行,计数器自增
    $newRow.insertBefore($button);
    rowIndex++;
  });
});

原有HTML代码翻译调整后如下

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="heading">请选择预约时段</h3>
<div class="form-wrapper">
  <form action="#" id="date-form" name="date-form" method="POST">
    <div class="period-row">
      <label for="start">开始时间:</label>
      <input type="datetime-local" name="start[]" id="start">
      <label for="end">结束时间:</label>
      <input type="datetime-local" name="end[]" id="end">
    </div>
    <input type="button" id="add-row" name="add-row" value="新增时段" />
    <button type="submit">提交</button>
  </form>
</div>

补充说明:你的输入框name属性已经设置为数组格式start[]/end[],提交表单时后台可以直接拿到所有时段的时间数组,不需要额外修改name属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:24:02