如何创建子子菜单?

时间:2013-02-22 09:54:08

标签: jquery html css json jquery-ui

创建jquery-menu时遇到问题。我从json对象创建了一个水平菜单。 我的页面是

var data = [
    {
    "parent": "Home",
    "child": [

            ]
    },
    {
    "parent": "Instructions",
    "child": [

            ]
    },

    {
    "parent": "Administration",
    "child": [
            {"title":"Recruitment"},
            {"title":"Management"},
            {"title":"Relations"}
            ]
    },
    ];

这里我有3个子子字段用于字段'招募'。如何使用json创建子子?

1 个答案:

答案 0 :(得分:1)

有一个代码可以为第3级创建HTML结构,您需要自己设置样式:

var data = [
{
    "parent": "Home",
    "child": [
            ]
},
{
    "parent": "Instructions",
    "child": [
       {
           "title":"Recruitment",
           "subchild": [
               {"title":"sub1"},
               {"title":"sub2"},
               {"title":"sub3"}
           ]
       },
        {"title":"Management"},
        {"title":"Relations"}
        ]
},
{
    "parent": "Administration",
    "child": [
        {"title":"Recruitment"},
        {"title":"Management"},
        {"title":"Relations"}
        ]
    },
];
$(function() {
    $('.nav-child').hover(function(){
    $('.parent-menu').css('background','red');
    });
    var nav = $("#nav");
    $.each(data,function(idx, obj){
        if(obj.child.length>0)
        {
            nav.append('<li><a href="#" class="parent-menu">'+obj.parent+'</a><ul class="child-list" id="'+obj.parent+'">'); //Create Parent menu and attach Child menu items list with ID same as parent menu name.
            var parent = $("#"+obj.parent); //Select this parent to insert child items.

            //Insert child menu items.
            $.each(obj.child, function(idx, childobj){
                var childid = obj.parent + '-item-' + idx;
                parent.append('<li class="nav-child" id="'+childid+'"><a href="#">'+childobj.title+'</a></li>');

                //insert subchild items
                if(childobj.subchild != undefined && childobj.subchild.length>0){
                    var child = $("#"+childid); //Select child element to insert subchild items.
                    child.append('<ul class="subchild-list"></ul>');
                    var ul = $(child).find('ul');

                    $.each(childobj.subchild, function(index, subchildobj){
                        ul.append('<li class="nav-subchild"><a href="#">'+subchildobj.title+'</a></li>');                
                    });   
                }
            });
            nav.append('</ul></li>'); //Close each tag.
        }
        else
        {
            nav.append('<li><a href="#">'+obj.parent+'</a></li>'); //No child menu items present, just create parent menu.
        }
    });
    ( "#nav" ).menu();
});