实现jQuery按钮遍历DOM所有层级元素(含子元素)的功能
实现点击按钮递归遍历DOM元素(深度优先)
核心思路是先按深度优先顺序收集所有需要遍历的DOM元素,维护一个当前遍历的索引,点击按钮时切换到列表的下一个元素,逻辑更清晰且不易出错。
修正后的完整代码
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1>jQuery next() example</h1> <div id="start">This is div 1 <div>div 1 child</div> </div> <p>This is paragrah 1</p> <div>This is div 2 <div>div 2 child</div> </div> <p>This is paragrah 2</p> <div> <ul> <li>List 1</li> <li>List 2</li> <li>List 3</li> </ul> </div> <div>This is div 3 <div>div 3 child</div> </div> <br/><br/><br/> <br/><br/><br/> <button id="nextButton1">next</button>
CSS
div, p { display: block; width: 110px; height: 40px; margin: 2px 8px 64px 8px; float: left; border: 1px blue solid; } #nextButton1 { display: block; padding-left: 50px; } li { border: 1px solid blue; padding: 10px 0; }
JavaScript
// 深度优先遍历,收集指定类型的DOM元素 function traverseDepthFirst($element, result = []) { // 只收集需要遍历的元素类型 if ($element.is('div, p, li')) { result.push($element); } // 递归遍历子元素 $element.children().each(function() { traverseDepthFirst($(this), result); }); return result; } // 初始化遍历列表:先收集起始元素及其子元素,再收集后续同级元素及其子元素 const $startElement = $("#start"); const elementList = traverseDepthFirst($startElement); $startElement.nextAll().each(function() { traverseDepthFirst($(this), elementList); }); let currentIndex = 0; // 高亮初始元素 elementList[currentIndex].css("background", "red"); $("#nextButton1").click(function() { // 清除所有元素的高亮状态 $("div,p,li").css("background", ""); // 切换到下一个元素,到达末尾后循环回到开头 currentIndex = (currentIndex + 1) % elementList.length; // 高亮当前选中的元素 elementList[currentIndex].css("background", "red"); });
关键逻辑说明
traverseDepthFirst函数:实现深度优先遍历规则,确保先遍历当前元素的所有子元素,再处理同级后续元素,完全匹配递归遍历DOM层级的需求。- 遍历列表初始化:一次性收集所有需要遍历的元素,避免每次点击时动态查找元素导致的逻辑混乱。
- 点击事件:通过索引切换元素,循环遍历整个列表,每次操作只需要维护索引和高亮状态,逻辑简洁稳定。
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

