[英]Get multidimensional array from ordered list
我有一個簡單的嵌套列表。
<ol id="draggable" class="nested-sort">
<li data-id="1">Lion</li>
<li data-id="2">Snake</li>
<li data-id="3">Butterfly
<ol data-id="3">
<li data-id="31">Fish</li>
<li data-id="32">Cat</li>
<li data-id="33">Monkey</li>
</ol>
</li>
<li data-id="4">Parrot</li>
</ol>
我想將<li>
的所有 ID 作為一個多維數組。 因此我嘗試使用 jQuery 的.each()
,但它只返回一次迭代。
$( "#draggable li" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
這導致以下 output:
0: Lion
1: Snake
2: Butterfly
Fish
Cat
Monkey
3: Fish
4: Cat
5: Monkey
6: Parrot
所以,首先讓你的生活更輕松一點,因為 text() 做了它應該做的,即返回元素的完整內容:在 li 的標題周圍添加一個 span,如下所示:
<ol id="draggable" class="nested-sort">
<li data-id="1"><span>Lion</span></li>
<li data-id="2"><span>Snake</span></li>
<li data-id="3"><span>Butterfly</span>
<ol data-id="3">
<li data-id="31"><span>Fish</span></li>
<li data-id="32"><span>Cat</span></li>
<li data-id="33"><span>Monkey<span></li>
</ol>
</li>
<li data-id="4"><span>Parrot</span></li>
</ol>
然后代碼如下:
$(document).ready(function(){
var res = {};
parse($("#draggable"), res);
console.log(res);
});
function parse(obj, result) {
$("li", obj).each(function(index){
result[index] = {'libelle': $("span", this).first().text(), 'sub': {}};
parse($("ol", this), result[index]['sub']);
});
}
Output:
{
"0": {
"libelle": "Lion",
"sub": {}
},
"1": {
"libelle": "Snake",
"sub": {}
},
"2": {
"libelle": "Butterfly",
"sub": {
"0": {
"libelle": "Fish",
"sub": {}
},
"1": {
"libelle": "Cat",
"sub": {}
},
"2": {
"libelle": "Monkey",
"sub": {}
}
}
},
"3": {
"libelle": "Fish",
"sub": {}
},
"4": {
"libelle": "Cat",
"sub": {}
},
"5": {
"libelle": "Monkey",
"sub": {}
},
"6": {
"libelle": "Parrot",
"sub": {}
}
}
高溫高壓
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.