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

jQuery循环重复生成相同对象,select2下拉选项多次重复创建问题

问题根因

你的重复生成问题是嵌套循环逻辑错误导致的:

  • 外层遍历后端返回的所有选项数组data.data,内层又遍历了URL拆分出来的选中ID数组myArr
  • 每1条后端返回的选项数据,都会完整执行myArr.length次循环,每次循环都会新增1个option,最终option总数为data.data.length * myArr.length,所以重复次数和URL拆分的数组长度完全一致。
修复方案

先将选中的ID数组转成数字集合,后续判断是否选中仅需O(1)复杂度,且每个后端选项只会生成1次option:

// 将URL选中的ID转为数字Set,方便快速匹配
const selectedIdSet = new Set(urlProjects.split(',').map(id => parseInt(id)))
const projectsArr = []

// 批量新增前先清空原有option,避免DOM残留
element.empty()

// 仅需遍历一次后端返回的所有选项
for (let i = 0; i < data.data.length; i++) {
  const currentItem = data.data[i]
  const isSelected = selectedIdSet.has(currentItem.id)
  // 生成option,直接传入选中状态
  const option = new Option(currentItem.name, currentItem.id, false, isSelected)
  element.select2().append(option)
  // 收集选中的ID
  if (isSelected) {
    projectsArr.push(currentItem.id)
  }
}
可选优化

如果项目不允许使用Set,也可以用数组includes方法实现选中判断,仅适合数据量较小的场景:

const selectedIdArr = urlProjects.split(',').map(id => parseInt(id))
// 判断逻辑替换为
const isSelected = selectedIdArr.includes(currentItem.id)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:36:04