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

如何遍历类的子元素动态提取以#开头的门店编号?

遍历子元素提取门店编号的实现方案

当然可以通过遍历目标容器的子元素来提取以#开头的门店编号,下面是具体的实现思路和代码示例:

核心思路

  1. 定位到包含取件地址的父容器.Test-order-details-delivery-info
  2. 遍历该容器下的所有直接子元素
  3. 对每个子元素的文本内容进行正则匹配,捕获#后的连续数字
  4. 找到目标编号后可停止遍历,提升效率

原生JavaScript实现代码

// 获取父容器元素
const deliverySection = document.querySelector('.Test-order-details-delivery-info');
let storeId = null;

// 遍历所有子元素
for (const child of deliverySection.children) {
  const textContent = child.textContent.trim();
  // 用正则匹配#开头的数字序列
  const idMatch = textContent.match(/#(\d+)/);
  
  if (idMatch) {
    storeId = idMatch[1]; // 提取捕获组中的纯数字编号
    break; // 找到目标后终止遍历,避免无效循环
  }
}

console.log('提取到的门店编号:', storeId); // 输出:2840

代码说明

  • querySelector精准定位父容器,确保只在目标区域内查找
  • 遍历children属性获取所有直接子元素,避免遍历深层嵌套的无关元素
  • 正则表达式/#(\d+)/专门匹配#后跟连续数字的模式,(\d+)作为捕获组,能直接提取纯数字编号
  • 找到匹配项后立即break,减少不必要的遍历操作

如果需要兼容更旧的浏览器,可将for...of循环替换为普通for循环:

const deliverySection = document.querySelector('.Test-order-details-delivery-info');
let storeId = null;
const children = deliverySection.children;

for (let i = 0; i < children.length; i++) {
  const textContent = children[i].textContent.trim();
  const idMatch = textContent.match(/#(\d+)/);
  
  if (idMatch) {
    storeId = idMatch[1];
    break;
  }
}

console.log('提取到的门店编号:', storeId);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:40:37