JSON和Jquery:从嵌套列表元素创建嵌套JSON [英] JSON and Jquery: Create nested JSON from nested list elements

查看:99
本文介绍了JSON和Jquery:从嵌套列表元素创建嵌套JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这个jsfiddle: http://jsfiddle.net/mfnxm/1/

I have created this jsfiddle: http://jsfiddle.net/mfnxm/1/

我正在尝试创建这个JSON:

I am trying to create this 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(从这里借用) - 但它没有为我创建节点元素:

Here's the javascript so far (borrowed from here) - but it is not creating the nodes elements for me:

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(无期间)。

Replace class=".sortable" in your HTML with class="sortable" (no period) at every occurrence.

您还需要更改 $(#tree ul)。children(li)。each(function() to $(#tree> ul>li ).each(function(){以避免冗余处理。

You also need to change $("#tree ul").children("li").each(function() to $("#tree > ul > "li").each(function() { to avoid redundant processing.

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

这篇关于JSON和Jquery:从嵌套列表元素创建嵌套JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆