以编程方式创建HTML列表并在点击

时间:2015-09-11 16:54:22

标签: javascript jquery json

我正在尝试从JSON数组构建HTML列表,如果列表对象包含子级数组“levels”,则单击列表项应将级别显示为后续列表项。默认情况下应隐藏级别,直到单击父级(参见下面的图形)

请参阅下面的代码尝试

$('#menuList ul')
         .append(
             $('<li></li>')
                 .append(
                     $('<a></a>')
                         .attr('href', '#')
                         .click(function (e) {

                             if (result.levels) {
                                 //if child levels, show levels on parent click
                                 var thelevels = result.levels;
                                 thelevels.forEach(function (level) {
                                     console.log(level);
                                 });
                             }
                             // where I handle the click event
                             doStuff(el, this.text);
                             e.preventDefault();
                         })
                         .data('myName', result.name)
                         .data('myNumber', result.mynumber)
                         .text(result.name)
                 )
         );

数据样本:

{
            "result_id": 7,
            "name": "My Name",
            "mynumber": "11",
            "levels": [
                0,
                1,
                2
            ]
        }

样机

enter image description here

1 个答案:

答案 0 :(得分:2)

根据您的回复,您可以执行以下操作:

// define construct table function, run through response and build table rows
// if there is levels, build levels, all in memory, not appended to DOM yet. 
function constructTable(response) { 
   var html = $("div"); // create div, but not append it yet to DOM

   for(var i = 0; i < response.length; i++) {
       var item =  response[i];

        var itemHtml = '<div class="item" data-id="' 
                + item.result_id
                + '">' 
                + '<p class="title">' 
                + item.name 
                + '</p>' 
                + '<div class="subItems">'
                + '</div>'
                + '</div>';

        var $itemHtml = $(itemHtml);

        if(item.levels.length) {
            for(var j = 0; j < item.levels.length; j++) {
               var subItem = item.levels[j];
               var subItemHtml = '<div class="subItem" data-id="' + subItem + '">' + "SubItem " + subItem + '</div>';

               $itemHtml.find('.subItems').append(subItemHtml);
           }
       }

       html.append($itemHtml);
   }
   return html;
}

var table = constructTable(response); // call function with response

$(".container").append(table); // append table to container at once, with all
// rows and sub items rendered.

// event for handling toggle of sub items.
$(".item").on("click", function() {
    $(this).find('.subItems').toggle();
});

这是jsfiddle:http://jsfiddle.net/kdynfezw/6/

但你应该看看Backbone和MarionetteJS及其CompositeView。

http://marionettejs.com/docs/v2.4.3/marionette.compositeview.html

它很好地处理这样的结构。