问题描述
假设我有一个无序的嵌套列表:
Lets say I have an unordered nested list:
<ul>
<li>Item a1</li>
<li>Item a2</li>
<li>Item a3</li>
<ul>
<li>Item b1</li>
<li>Item b2</li>
<li>Item b3</li>
<ul>
<li>Item c1</li>
<li>Item c2</li>
<li>Item c3</li>
</ul>
<li>Item b4</li>
</ul>
<li>Item a4</li>
</ul>
我需要遍历它并将其保存在二维数组中(最终我只是想尝试将其转换为JSON实体)我可以使用Jquery和/或Javascript。我该怎么办?
I need to traverse it and save it in a two dimensional array (ultimately I'm just trying to convert it into a JSON entity) I am allowed to use both Jquery AND/OR Javascript. How should I proceed?
谢谢
推荐答案
我不是确切地说你想要的结果数据结构是什么样的,但是这(使用了一些jQuery):
I'm not sure exactly what you want the resulting data structure to look like, but this (which uses some jQuery):
$(function() {
var result = {};
function createNewLevel(parent,items) {
var length = items.length;
for(var i = 0; i < length; i++) {
if(items[i].tagName == 'UL') {
parent['ul' + i] = {};
createNewLevel(parent['ul' + i],$(items[i]).children().get());
} else {
parent['li' + i] = $(items[i]).text();
}
}
}
createNewLevel(result, $('ul:first').get());
console.log(result);
});
...会产生这种结构
... would produce this structure
{
ul0: {
li0: "Item a1",
li1: "Item a2",
li2: "Item a3",
li4: "Item a4",
ul3: {
li0: "Item b1",
li1: "Item b2",
li2: "Item b3",
li4: "Item b4",
ul3: {
li0: "Item c1",
li1: "Item c2",
li2: "Item c3"
}
}
}
}
如果需要,可以相当容易地调整以改变结果结构的细节。
It could be fairly easily tweaked to alter details of the resulting structure if needed.
请注意,这是一个javascript对象。如果你真的需要一个JSON对象,那么你只需要使用 var jsonResult = JSON.stringify(result);
Please note that this is a javascript object. If you actually need a JSON object, then you just need to convert it using var jsonResult = JSON.stringify( result );
这篇关于使用Javascript / Jquery遍历无序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!