使用Javascript / Jquery遍历无序列表
可以说我有一个无序的嵌套列表:
- Item a1
- Item a2
- Item a3
- Item b1
- Item b2
- Item b3
- Item c1
- Item c2
- Item c3
- Item b4
- Item a4
我需要遍历它并将其保存在二维数组中(最终我只是尝试将其转换为JSON实体)我可以使用Jquery和/或Javascript。 我该怎么办?
谢谢
我不确定你想要的结果数据结构是什么样的,但是这(使用了一些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); });
......会产生这种结构
{ 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" } } } }
如果需要,可以相当容易地调整以改变结果结构的细节。
请注意,这是一个javascript对象。 如果你确实需要一个JSON对象,那么你只需要使用var jsonResult = JSON.stringify( result );
转换它var jsonResult = JSON.stringify( result );
function traversing(ul) { for(var index=0;index0){ traversing(ul.childNodes[index]); } //perform other operation } }
用JQuery试试:
$.each($("li"), function(index, value) { alert(value); });