簡體   English   中英

如何遍歷DOM准備樹結構數組

[英]How to traverse DOM to prepare tree structure array

我想通過使用 Javascript/jQuery 遍歷 DOM 來准備一個嵌套數組。 感興趣的元素在#container元素中,要么具有dot類,要么是input元素。

我想准備像[name,name1,[name2]]這樣的數組。 我在這里使用的主要是遞歸等技術。 但我無法讓它工作:

小提琴

 $(document).ready(function(){ var arr = []; function recurse(parent, arr){ var temp = []; parent.find('*').each(function(){ if($(this).is('input')){ if($(this).parents('.dot').length==1){ console.log($(this)); temp.push($(this).attr('id')) } } if($(this).is('.dot')){ recurse($(this), arr); } }); arr.push(temp); return arr; } var elm = $('#container').find('.dot:first'); console.log(recurse(elm, arr)); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"> <div class="dot"> <div class="dot"> <input type="password" id="name2" name="name2"> </div> <input type="text" id="name" name="name"> <input type="password" id="name1" name="name1"> </div> </div>

以下是您如何使其工作。 無需將arr作為參數傳遞:

 function recurse($parent) { var arr = []; $parent.children('.dot, input').each(function(){ arr.push($(this).is('input') ? $(this).attr('id') : recurse($(this))); }); return arr; } $(function () { var elm = $('#container>.dot:first'); console.log(recurse(elm)); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"> <div class="dot"> <div class="dot"> <input type="password" id="name2" name="name2"> </div> <input type="text" id="name" name="name"> <input type="password" id="name1" name="name1"> </div> </div>

這是使用vanilla JS解決它的方法

 const el = document.querySelector('#container > .dot'); function recurse(containerEl) { const result = []; const tmp = []; // used to preserve the order [name, name1, [name2]] const childrenCollection = containerEl.children; for (let i = 0; i < childrenCollection.length; i++) { if (childrenCollection[i].tagName === 'DIV') { tmp.push(recurse(childrenCollection[i])); } else { // use this line if you want to fill the array with elements // result.push(childrenCollection[i]); // use this line if you just want to retrieve the name attribute result.push(childrenCollection[i].name); } } return result.concat(tmp); } console.log(recurse(el));
 <div id="container"> <div class="dot"> <div class="dot"> <input type="password" id="name2" name="name2"> </div> <input type="text" id="name" name="name"> <input type="password" id="name1" name="name1"> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM