簡體   English   中英

JSON和Jquery:從嵌套列表元素創建嵌套JSON

[英]JSON and Jquery: Create nested JSON from nested list elements

我創建了這個jsfiddle: http : //jsfiddle.net/mfnxm/1/

我正在嘗試創建此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( 從此處借來的 )-但這不是為我創建nodes元素:

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));

我想念什么? 謝謝!

每次出現時,將HTML中的class=".sortable"替換為class="sortable" (無句點)。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM