2013-05-14 79 views
0

我创建了一个函数,可以将任意类型的JSON数据遍历到UL/LI中。现在我需要做相反的事情,并将UL/LI的背景转换为JSON对象。如果可能,我想在JQuery中执行此操作。那么如何将我的嵌套UL/LI返回到其原始JSON对象?遍历HTML到JSON

var traverseJson = function(jsonObj) { 
    "use strict"; 
    var htmlOut = "", 
    value, 
    inputv, 
    prop; 
    for (prop in jsonObj) { 
    if (jsonObj.hasOwnProperty(prop)) { 
     value = jsonObj[prop]; 
     switch (typeof value){ 
     case "object": 
      htmlOut += "<li><b>" + prop + "</b><span>" + traverseJson(value) + "</span></li>"; 
      break; 
     default: 
      inputv = "<span>" + value + "</span>"; 
      htmlOut += "<li class='val'><b>" + prop + ":</b>" + inputv + "</li>"; 
      break; 
     } 
    } 
    } 
    return "<ul>" + htmlOut + "</ul>"; 
}; 
+1

不知道你们是否意识到这是一个递归函数。不知何故,我需要检查它是否是UL或LI不是吗? – user176855

+0

我使用[JSHint](http://www.jshint.com/)清理了代码。有几件事需要修复。当你使用'for ... in'时,你应该总是[使用'.hasOwnProperty'来过滤循环](http://yuiblog.com/blog/2006/09/26/for-in-intrigue/)。此外,由于您从未声明过“prop”,因此它成为[隐式全球](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html)。 'self'不是JS中的关键字,你可以调用'traverseJson',因为它已经在你的范围内了。如果'traverseJson'是一个对象的方法,则可以使用'this.traverseJson'来引用它。 –

+0

谢谢无用,我几乎看到你的编辑生活。好点! – user176855

回答

2

那么你要做的是迭代li元素。

function parseList() { 
    var outObj = {}; 

    $("li").each(function() { 
     var propName = $(this).children("b").html(); 
     var propValue = $(this).children("span").html(); 
     outObj[propName] = propValue; 
    }); 

    return outObj; 
} 
+0

我认为这是其中的一部分,但我需要无限下降。因为它可能在对象中有对象... – user176855

1

像这样的东西应该工作。它需要一个表示div的jQuery对象,并找到其中的第一个ul标记并向下遍历,直到找到不包含ul标记的li标记。

var divToJson = function ($div) { 
    "use strict"; 
    var traverseUl = function ($ul) { 
    var output = {}, 
     $li = $ul.children('li'); 
    $li.each(function() { 
     var $this = $(this), 
     propName = $this.children('b').text(), 
     $propValue = $this.children('span'), 
     $subList = $propValue.find('ul').first(); 

     if ($subList.length > 0) { 
      output[propName] = traverseUl($subList); 
     } else { 
      output[propName] = $propValue.text(); 
     } 
    }); 
    return output; 
    }; 

    return traverseUl($div.find('ul').first()); 
}; 

var theDiv = $('#somediv'); 
console.log(divToJson(theDiv));