简而言之,我想将UL列表转换为javascript / jquery数组。我的问题是UL可以有任何长度和深度的嵌套。
这是一个样本UL:
<div id="main">
<ul>
<li>
<span>HOME</span>
<ul>
<li><span>Page 1</span></li>
<li><span>Page 2</span></li>
<li>
<span>Page 3</span>
<ul>
<li><span>Page a</span></li>
<li><span>Page b</span></li>
<li><span>Page c</span></li>
<li>
<span>Page X</span>
<ul>
<li><span>Page d</span></li>
<li><span>Page e</span></li>
<li><span>Page f</span></li>
<li><span>Page g</span></li>
</ul>
</li>
</ul>
</li>
<li><span>Page 4</span></li>
</ul>
</li>
</ul>
</div>
我在jquery中有一个基本的每个循环,它只通过第一个嵌套。我需要它继续通过任何有孩子的li和生成的数组以匹配嵌套格式:
var arr = [];
$("#main > ul > li").each(function() {
var elem = {
brand: $(this).find(">span:first").text(),
children: []
};
$(this).find(">ul>li").each(function() {
elem.children.push($(this).find('span:first').text());
});
arr.push(elem);
});
console.log(arr);
以下是它的输出:
答案 0 :(得分:2)
实现目标的最佳方法是通过递归:
var list = [];
$("#main > ul > li").each(function() {
list.push(buildObject($(this)));
});
function buildObject(parent){
var obj = {
brand: parent.find(">span:first").text(),
children: [],
}
parent.find(">ul>li").each(function() {
obj.children.push(buildObject($(this)));
});
return obj;
}
console.log(list);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<ul>
<li>
<span>HOME</span>
<ul>
<li><span>Page 1</span></li>
<li><span>Page 2</span></li>
<li>
<span>Page 3</span>
<ul>
<li><span>Page a</span></li>
<li><span>Page b</span></li>
<li><span>Page c</span></li>
<li>
<span>Page X</span>
<ul>
<li><span>Page d</span></li>
<li><span>Page e</span></li>
<li><span>Page f</span></li>
<li><span>Page g</span></li>
</ul>
</li>
</ul>
</li>
<li><span>Page 4</span></li>
</ul>
</li>
</ul>
</div>
&#13;