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

如何用jQuery区分两种sectionId格式的输入框并分别取值?

区分两种ID格式的Input元素并分别收集值

要分别获取sectionId_数字(section)和sectionId_数字_数字(subsection)这两种Input的值并存入不同数组,你可以通过筛选匹配ID格式的方式来实现,下面提供两种简洁高效的方案:

方案1:使用正则表达式精准匹配ID格式

通过filter()方法结合正则表达式,精准筛选出符合两种格式的元素,再分别遍历收集值:

// 初始化存储值的数组
const sectionValues = [];
const subSectionValues = [];

// 筛选并收集section类型的input值
$(".row")
  .find("input[id^='sectionId_']")
  .filter(function() {
    // 匹配只有一个下划线的ID:sectionId_0、sectionId_1等
    return this.id.match(/^sectionId_\d+$/) !== null;
  })
  .each(function() {
    sectionValues.push($(this).val());
  });

// 筛选并收集subsection类型的input值
$(".row")
  .find("input[id^='sectionId_']")
  .filter(function() {
    // 匹配有两个下划线的ID:sectionId_0_0、sectionId_1_2等
    return this.id.match(/^sectionId_\d+_\d+$/) !== null;
  })
  .each(function() {
    subSectionValues.push($(this).val());
  });

方案2:一次遍历完成分类(更高效)

如果不想多次查询DOM,可以一次遍历所有目标元素,通过统计ID中下划线的数量来区分类型:

const sectionValues = [];
const subSectionValues = [];

$(".row").find("input[id^='sectionId_']").each(function() {
  const id = this.id;
  // 统计ID中下划线的数量
  const underscoreNum = (id.match(/_/g) || []).length;
  
  if (underscoreNum === 1) {
    // 只有1个下划线,属于section
    sectionValues.push($(this).val());
  } else if (underscoreNum === 2) {
    // 有2个下划线,属于subsection
    subSectionValues.push($(this).val());
  }
});

补充说明

单纯的[id^='sectionId_']开头匹配选择器会同时选中两种ID格式的元素,所以必须通过额外的筛选逻辑来区分它们。上面两种方案都能精准区分这两种嵌套关系的元素,你可以根据自己的习惯选择使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:21:36