2011-10-28 51 views
4

我創造了這個的jsfiddle嵌套列表元素嵌套的JSON:http://jsfiddle.net/mfnxm/1/JSON和jQuery:創建一個從

我試圖創建這個JSON:

[{ 
"link":"/about", 
"title":"About", 
"nodes":[{ 
    "link":"/staff", 
    "title":"Staff", 
    "nodes":[{ 
     "link":"/heads", 
     "title":"Dept Heads" 
     },{ 
     "link":"/support", 
     "title":"Support" 
     }] 
    },{ 
    "link":"/location", 
    "title":"Location" 
    }] 
},{ 
"link":"/contact", 
"title":"Contact" 
}] 

從這個無序列表:

<div id="tree"> 
    <ul class=".sortable"> 
     <li><a href="/about">About</a> 
      <ul class=".sortable"> 
       <li><a href="/staff">Staff</a> 
        <ul class=".sortable"> 
         <li><a href="/heads">Dept Heads</a></li> 
         <li><a href="/support">Support</a></li> 
        </ul> 
       </li> 
       <li><a href="/location">Location</a></li> 
      </ul> 
     </li> 
     <li><a href="/contact">Contact</a></li> 
    </ul> 
</div> 

以下是目前爲止的JavaScript(borrowed from here) - 但它並沒有爲我創建節點元素:

var out = []; 
function processOneLi(node) {  
    var aNode = node.children("a:first"); 
    var retVal = { 
     "link": aNode.attr("href"), 
     "title": aNode.text() 
    }; 
    node.find("> .sortable > li").each(function() { 
     if (!retVal.hasOwnProperty("nodes")) { 
      retVal.nodes = []; 
     } 
     retVal.nodes.push(processOneLi($(this))); 
    }); 
    return retVal; 
} 
$("#tree ul").children("li").each(function() { 
    out.push(processOneLi($(this))); 
}); 

// Do something with data 
$('#d').text(JSON.stringify(out)); 

我錯過了什麼?謝謝!

回答

2

在您的HTML中將class=".sortable"替換爲class="sortable"(無期間)。

您還需要將$("#tree ul").children("li").each(function()更改爲$("#tree > ul > "li").each(function() {以避免冗餘處理。

http://jsfiddle.net/mblase75/mfnxm/2/