简体   繁体   English

使用Javascript / Jquery遍历无序列表

[英]Traversing unordered lists using Javascript/Jquery

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>

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. 我需要遍历并将其保存在二维数组中(最终,我只是试图将其转换为JSON实体)我被允许同时使用Jquery和/或Javascript。 How should I proceed? 我应该如何进行?

Thanks 谢谢

function traversing(ul)
{
     for(var index=0;index<ul.childNodes.length;index++){
          if(ul.childNodes[index].childNodes.length>0){
              traversing(ul.childNodes[index]);
          }
          //perform other operation
     }
}

I'm not sure exactly what you want the resulting data structure to look like, but this (which uses some jQuery): 我不确定您想要的结果数据结构是什么样子,但这(使用一些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. 如果需要,可以很容易地对其进行调整以更改生成的结构的细节。

Please note that this is a javascript object. 请注意,这是一个javascript对象。 If you actually need a JSON object, then you just need to convert it using var jsonResult = JSON.stringify( result ); 如果您确实需要JSON对象,则只需使用var jsonResult = JSON.stringify( result );进行转换var jsonResult = JSON.stringify( result );

With JQuery try: 使用JQuery尝试:

$.each($("li"), function(index, value) { 
  alert(value); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM