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

如何使用jQuery在动态增删元素时设置递增ID

实现动态添加列的递增ID方案

没问题,咱们来搞定这个动态添加元素时ID自动递增的需求!这里有两种靠谱的实现方式,你可以根据场景选择:

方式一:全局变量跟踪序号(简单直接)

这种方式用一个全局变量记录当前的ID编号,每次添加就自增,不管元素有没有被删除,新元素的ID都会持续递增,和你给出的示例逻辑完全一致:

修改后的JavaScript代码:

// 初始化序号,从1开始(对应第一个gallery1)
let galleryIdCounter = 1;

$(".imgAdd").click(function(){
  // 用当前计数器值生成ID
  const newId = `gallery${galleryIdCounter}`;
  // 插入新的列元素,把生成的ID替换进去
  $(this).closest(".row").find('.imgAdd').before(`
    <div class="col-sm-4 imgUp">
      <input id="${newId}" class="uploadFile tourbanner">
      <i class="fa fa-times del"></i>
    </div>
  `);
  // 计数器自增,为下一次添加做准备
  galleryIdCounter++;
});

$(document).on("click", "i.del" , function() {
  $(this).parent().remove();
});

对应的HTML结构(无需修改):

<div class="row" id="container"> 
  <!-- 动态添加的列将放在此处 --> 
  <i class="fa fa-plus imgAdd"></i> 
</div>

方式二:基于现有元素数量动态计算序号(更严谨,适配初始已有元素的场景)

如果你的页面加载时已经有几个预先添加的imgUp元素,这种方式会自动统计现有数量,确保新元素的ID和已有元素连贯:

修改后的JavaScript代码:

$(".imgAdd").click(function(){
  // 统计当前container里已经有的imgUp元素数量
  const existingCount = $("#container .imgUp").length;
  // 新ID的序号是现有数量+1
  const newId = `gallery${existingCount + 1}`;
  // 插入新元素
  $(this).closest(".row").find('.imgAdd').before(`
    <div class="col-sm-4 imgUp">
      <input id="${newId}" class="uploadFile tourbanner">
      <i class="fa fa-times del"></i>
    </div>
  `);
});

$(document).on("click", "i.del" , function() {
  $(this).parent().remove();
});

比如页面初始有1个imgUp元素,点击添加后会生成gallery2,再点击生成gallery3,完美匹配你的需求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 14:37:51