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

如何用jQuery遍历不同ID标签及动态添加的Django formset表单

关于jQuery遍历元素的解决方案

一、遍历所有带不同ID的标签

如果只是想遍历页面上所有拥有ID属性的元素,不管ID是什么,用jQuery的属性选择器配合each()方法就能轻松实现:

// 选中所有带有id属性的元素,逐个遍历
$('[id]').each(function() {
  const currentId = $(this).attr('id');
  console.log(`当前元素ID:${currentId}`);
  // 这里可以添加你对每个元素的自定义操作,比如修改内容、获取值等
});

简单解释下:[id]是jQuery的属性选择器,会匹配所有包含id属性的DOM元素;each()方法则会逐个迭代这些元素,this指向当前正在处理的DOM节点,用$(this)可以把它转换成jQuery对象来操作。

二、针对Django Formset的遍历方案

你的场景是遍历动态添加的Django formset表单,元素ID格式是id_lines-0-label、id_lines-0-description这类,我给你两种实用的方案,按需选择:

方案1:依赖表单行容器(推荐)

通常Django formset的每个表单会被包裹在一个统一的容器里(比如class为formset-row的div),这种情况下可以先遍历容器,再在容器内找对应字段,结构更清晰,也不怕ID格式变动:

假设你的HTML结构是这样的:

<!-- 已有的表单行 -->
<div class="formset-row">
  <input type="text" id="id_lines-0-label" name="lines-0-label">
  <textarea id="id_lines-0-description" name="lines-0-description"></textarea>
</div>
<!-- 新增的表单行也会自动带上formset-row类 -->
<div class="formset-row">
  <input type="text" id="id_lines-1-label" name="lines-1-label">
  <textarea id="id_lines-1-description" name="lines-1-description"></textarea>
</div>

对应的jQuery代码:

// 封装成函数,方便调用(比如添加表单后执行)
function traverseFormsetRows() {
  $('.formset-row').each(function(rowIndex) {
    const $currentRow = $(this);
    // 在当前行内找到label和description字段
    const $labelInput = $currentRow.find('[id$="-label"]');
    const $descriptionInput = $currentRow.find('[id$="-description"]');
    
    // 获取字段值或执行其他操作
    const labelValue = $labelInput.val();
    const descriptionValue = $descriptionInput.val();
    
    console.log(`第${rowIndex + 1}个表单:标签=${labelValue},描述=${descriptionValue}`);
  });
}

// 例子:点击添加按钮后,先添加表单再执行遍历
$('.add-form-btn').click(function() {
  // 这里是你的表单添加逻辑(比如Django formset自带的添加函数)
  // ...
  
  // 新增完成后调用遍历函数
  traverseFormsetRows();
});

这个方案的好处是,不管formset的ID怎么生成,只要新增的表单行带上formset-row类,就能被正确遍历到。

方案2:通过ID索引关联字段

如果你的表单没有统一的外层容器,也可以直接通过ID里的索引值来匹配对应的label和description:

function traverseFormsetById() {
  // 先找到所有label字段
  $('[id^="id_lines-"][id$="-label"]').each(function() {
    const $label = $(this);
    // 从ID中提取索引:比如"id_lines-0-label"分割后取第2个部分
    const index = $label.attr('id').split('-')[1];
    // 通过索引找到对应的description字段
    const $description = $(`#id_lines-${index}-description`);
    
    // 执行操作
    console.log(`索引${index}的表单:标签=${$label.val()},描述=${$description.val()}`);
  });
}

这种方法完全依赖ID的格式,适合结构固定的场景,不需要额外的容器类。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:21:18