jQuery:循环统计各child类元素数量(替代length方法)
解决方法:统计指定类别的元素数量(避开.length,保证性能)
首先,咱们核心要做到两点:只统计带.children类的childN元素,完全不使用.length相关属性/方法,同时还要保证性能(减少DOM查询次数)。下面给你两种可行的方案:
方案一:jQuery遍历+原生类处理(适合仅禁用jQuery.length的场景)
这个方案只做一次DOM查询,然后遍历元素逐个计数,完全避开jQuery的.length:
// 初始化一个对象存储统计结果 const categoryCounts = {}; // 只查询带.children类的元素,自动排除其他div $('.children').each(function() { // 从当前元素的类列表中提取child开头的类别 const childCategory = Array.from(this.classList).find(cls => cls.startsWith('child')); if (childCategory) { // 计数:存在则加1,不存在则初始化为1 categoryCounts[childCategory] = (categoryCounts[childCategory] || 0) + 1; } }); // 打印结果,比如categoryCounts.child1就是3,child2是5 console.log(categoryCounts);
为什么这个方案性能好?
- 仅做一次DOM查询获取所有目标元素,避免重复遍历DOM
- 使用原生
classList和数组方法处理类名,比纯jQuery操作更快 - 选择器
.children精准过滤了无关元素,不用额外判断
方案二:纯原生DOM遍历(完全避开length属性/方法)
如果连原生DOM元素集合的length也不能用,那可以用nextElementSibling逐个查找目标元素,全程不用length:
const categoryCounts = {}; // 找到第一个带.children类的元素 let currentElement = document.querySelector('.children'); while (currentElement) { // 提取child开头的类别 const childCategory = Array.from(currentElement.classList).find(cls => cls.startsWith('child')); if (childCategory) { categoryCounts[childCategory] = (categoryCounts[childCategory] || 0) + 1; } // 找到下一个带.children类的元素,跳过无关div currentElement = currentElement.nextElementSibling; while (currentElement && !currentElement.classList.contains('children')) { currentElement = currentElement.nextElementSibling; } } // 查看统计结果 console.log(categoryCounts);
这个方案的优势:
- 完全不依赖任何
length属性/方法,彻底满足要求 - 逐个遍历目标元素,没有多余的DOM查询,性能高效
- 自动跳过非
.children的div,不会统计无关元素
内容的提问来源于stack exchange,提问作者djmg




