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

MVC项目中jQuery克隆.item_details类div时多次克隆重复已有项求助

问题核心原因

  • 选择器使用错误:你的JS代码中使用ID选择器$('#item_details')获取待克隆元素,但HTML中待克隆的div仅设置了class="item_details",没有对应ID。第一次点击时页面仅存在1个该类元素,巧合匹配到了目标;第二次点击时页面已经存在多个.item_details元素,会被全部选中克隆,因此出现一次新增多个项的问题。
  • 未单独保留克隆母版:你目前将原始待克隆项和已生成的业务项放在同一个容器中,每次选中都会包含之前已经克隆生成的项,进一步放大了重复克隆的问题。

修复方案

第一步:HTML调整

单独新增一个隐藏的克隆母版,和业务生成项隔离开,避免后续选择时互相干扰,同时移除重复的ID属性:

<!-- 新增:克隆母版,默认隐藏,仅作为克隆模板使用 -->
<div id="item_details_template" style="display:none;">
  @Html.EditorFor(x => Model.Formulaire.Detail.DetailCmp.ListeCmpt.ListeCmptETS[i].ListeHospitalisation.Liste_Hospitalisation[0])
  <a href="#" name="remove_item" class='remove'>删除</a>
</div>

<div id="ListeFraisHospitalisation@(i)_Global">
@for (int y = 0; y < Model.Formulaire.Detail.DetailCmp.ListeCmpt.ListeCmptETS[i].ListeHospitalisation.Liste_Hospitalisation.Count; y++) { 
  <div style="border:1px solid black;" id="FraisHospitalisation@(i)_@(y)" class="classHospitalisation@(i)">
    <div class="item_details">
      @Html.EditorFor(x => Model.Formulaire.Detail.DetailCmp.ListeCmpt.ListeCmptETS[i].ListeHospitalisation.Liste_Hospitalisation[y])
      <a href="#" name="remove_item" class='remove'>删除</a>
    </div>
  </div>
}
</div>

第二步:JS逻辑调整

改为选择固定的隐藏母版进行克隆,避免匹配到已生成的业务项:

var id = 0;
jQuery(document).ready(function() {
  var max = 10;
  jQuery('#add_item').click(function() {
    // 仅选择唯一的隐藏母版克隆
    var newItem = $('#item_details_template').clone(true);
    id++;
    newItem.find('input').val('');
    newItem.removeAttr('id');
    // 克隆后显示项
    newItem.show();
    newItem.insertBefore('.new_item_details');
    newItem.attr('id', 'new_' + id);
    
    // 可选补充:如果需要提交时MVC能正确绑定列表数据,需要同步修改新生成输入框的name属性,将索引替换为当前id值
  });

  // 补充删除功能的事件绑定(用事件委托适配新增项)
  jQuery(document).on('click', '.remove', function() {
    jQuery(this).closest('.item_details').parent().remove();
  });
});

其他注意事项

不要给删除按钮设置固定IDid="remove_item",同一页面ID重复会导致事件绑定、元素选择异常,直接通过class绑定事件即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:45:08