Buscar contenidos

viernes, 28 de febrero de 2020

Building Menu from JSON

Link 





    var data =
    [
        {           
            "id": "1"  ,
            "parentid": "0",
            "text": "Chocolate Beverage"
        }, {
            "id": "2",
            "parentid": "1",
            "text": "Lorem Ipsum es simplemente el texto de relleno"
        }, {
            "id": "3",
            "parentid": "1",
            "text": "Lorem Ipsum es simplemente el texto de relleno"
            }, {
                "id": "4",
                "parentid": "3",
            "text": "Lorem Ipsum es simplemente el texto de relleno"
            }, {
                "id": "5",
                "parentid": "4",
            "text": "Lorem Ipsum es simplemente el texto de relleno"
            }, {
                "id": "6",
                "parentid": "5",
            "text": "Lorem Ipsum es simplemente el texto de relleno"
            }
    ];


    var builddata = function () {
        var source = [];
        var items = [];
        // build hierarchical source.
        for (i = 0; i < data.length; i++) {
            var item = data[i];
            var label = item["text"];
            var parentid = item["parentid"];
            var id = item["id"];

            if (items[parentid]) {
                var item2 = { parentid: parentid, label: label, item: item };
                if (!items[parentid].items) {
                    items[parentid].items = [];
                }
                items[parentid].items[items[parentid].items.length] = item2;
                items[id] = item2;
            }
            else {
                items[id] = { parentid: parentid, label: label, item: item };
                source[id] = items[id];
            }
        }
        return source;
    };

    var source = builddata();

    var buildUL = function (parent, items) {
        $.each(items, function () {
            if (this.label) {
                // create LI element and append it to the parent element.
                var li = $("<li><a href='#'>" + this.label + "</a></li>");
                li.appendTo(parent);
                li.addClass("cn-dropdown-item has-down");
                // if there are sub items, call the buildUL function.
                if (this.items && this.items.length > 0) {
                    var ul = $("<ul class='dropdown'></ul>");
                    ul.appendTo(li);
                    buildUL(ul, this.items);
                }
            }
        });
    };

    var ul = $("<ul></ul>");   

    //ul.appendTo("#jqxMenu");
    buildUL(ul, source);

    var area_nav = $("#creditNav > div.classy-menu > div.classynav > ul");

    debugger

    area_nav.append(ul.html());

No hay comentarios:

Publicar un comentario