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

jQuery选择器如何组合id与类选择器选中元素并统计数量

问题原因

  • 你通过attr('id')获取到的id值仅为纯文本(比如box-1),没有带id选择器必需的#前缀,拼接后的选择器会被识别为查找标签名为box-1的元素,自然匹配不到任何内容
  • 页面存在多个类为multi-steps-wrapper的元素时,$('div.multi-steps-wrapper').attr('id')只会返回第一个匹配元素的id,若要指定其他容器需要修改元素选择逻辑

解决方案

方案1:直接组合选择器(固定目标容器为#box-1时推荐)

直接把id和类选择器按规则拼接即可,写法最简单:

const sectionCount = $("#box-1 .multi-steps-content section").length;
console.log(sectionCount); // 输出3

方案2:动态获取id拼接(需要动态适配不同容器时用)

给拿到的id值补上前缀#即可:

const targetDivId = $('div.multi-steps-wrapper').attr('id');
const sectionCount = $(`#${targetDivId} .multi-steps-content section`).length;
console.log(sectionCount); // 输出3

内容的提问来源于stack exchange,提问作者d.s

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:24:05