Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

javascript - Creating a Menu from JSON

I am trying to create a dynamic menu using jQuery UI.

I will be fetching entries from a JSON file and creating my menu items.I decided to do a small demo before i try this on a larger scale.Here's my fiddle which works the way i want it to work. Now I cant get this to work with a JSON file.

WORKING FIDDLE

Here is the JSON

var JSON = 
    {
       menu: 
          [
             {name: 'Croatia', link: '0', sub: null},
             {name: 'England', link: '1', sub: 
                [
                   {name: 'Arsenal',link: '0-0', sub: null},
                   {name: 'Liverpool',link: '0-1', sub: null},
                   {name: 'Manchester United',link: '0-2', sub: null}
                ]
             },
             {name: 'Spain', link: '2', sub: 
                [
                   {name: 'Barcelona',link: '2-0', sub: null},
                   {name: 'Real Madrid',link: '2-1', sub: null}
                ]
              },        
              {name: 'Germany', link: '3',sub: 
                [
                   {name: 'Bayern Munich',link: '3-1', sub: null},
                   {name: 'Borrusia Dortmund',link: '3-2', sub: null}
                ]
              }
          ]
    }

How can i design my entire menu using the values from the JSON where the Li's will be something like the following.

<li><a href="#3-2">Borrusia Dortmund</a>
</li>

EDIT: The question may sound like i have not tried anything, but i have. its just the JSON part which i cannot understand, Jsfiddle does not read it properly. I am wondering if my jSON is not formatted properly. Any help would be appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just iterate your JSON.menu array and generate the menu from it (renamed JSON -> data ...):

$(function () {
    var getMenuItem = function (itemData) {
        var item = $("<li>")
            .append(
        $("<a>", {
            href: '#' + itemData.link,
            html: itemData.name
        }));
        if (itemData.sub) {
            var subList = $("<ul>");
            $.each(itemData.sub, function () {
                subList.append(getMenuItem(this));
            });
            item.append(subList);
        }
        return item;
    };

    var $menu = $("#menu");
    $.each(data.menu, function () {
        $menu.append(
            getMenuItem(this)
        );
    });
    $menu.menu();
});

http://jsfiddle.net/9uhc3/5/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...