0

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

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

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

            ]
    },

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

在这里,我有 3 个子字段用于“招聘”字段。如何使用 json 创建子子项?

4

1 回答 1

1

有一个代码可以为您创建第三级的 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();
});
于 2013-02-22T12:59:38.997 回答