Jquery tree traversal - Nested Unordered list elements to JSON

后端 未结 3 1885
深忆病人
深忆病人 2020-12-18 10:52

Okay, Now I have an unordered list here:

  • Item A
3条回答
  •  被撕碎了的回忆
    2020-12-18 11:52

    The following source code is my solution. I think it's clear enough to show the principle to covert ul to json object. Good Luck :)

    $(function() {
    
      function buildJSON($li) {
        var subObj = { "name": $li.contents().eq(0).text().trim() };
        $li.children('ul').children().each(function() {
          if (!subObj.children) { subObj.children = []; }
          subObj.children.push(buildJSON($(this)));
        });
        return subObj;
      }
        
      var obj = buildJSON($("#ul-data").children());
      $('body').append('
    ').find('pre').append(JSON.stringify(obj, null, 2));
    
    });
    
    

提交回复
热议问题