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

如何使用jQuery分别统计每个无序列表对应的列表项数量

问题分析

你之前的代码调用$(".sidebar").find("ul").children().length时,会选中侧边栏下所有ul的所有直接子元素,统计的是全部li的总数量,自然得不到每个ul单独的计数。

修改方案

遍历每一个class为category-menu的ul节点,单独统计每个节点下的li数量即可,修改后的代码如下:

$(function(){
  // 获取所有目标ul集合
  const filterListMenu = $('.category-menu');
  // 遍历每个ul节点分别统计
  filterListMenu.each(function (index) {
    // $(this)指向当前遍历到的单个ul
    const currentLiCount = $(this).children('li').length;
    console.log(`第${index + 1}个category-menu ul的li数量:`, currentLiCount);
  })
});

运行效果

控制台会依次输出两个ul对应的li数量:

  • 第1个category-menu ul的li数量:6
  • 第2个category-menu ul的li数量:6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:24:00