How to add items to a unordered list
    using jquery

前端 未结 4 533
猫巷女王i
猫巷女王i 2020-12-07 14:11

In my json response, I want to loop through it using $.each and then append items to a

    element.

        $.each(data, function(         
    
    
            
    4条回答
    •  情歌与酒
      2020-12-07 14:33

      I decided to take redsquare's excellent answer and improve upon it a bit. Rather than adding HTML, I prefer to add jQuery objects. That way, I don't have to worry about escaping for HTML and what not.

      In this example, data contains an array of objects, parsed from JSON. Each object in the array has a .title property. I use jQuery's each function to loop through them.

      var items=[];
      $(data).each(function(index, Element) {
          items.push($('
    • ').text(Element.title)); }); $('#my_list').append.apply($('#my_list'), items);
    • I push a new jQuery object onto the items array, but with method chaining I can set properties ahead of time, such as .text.

      I then append the array of objects to the list

        using Lars Gersmann's method.

    提交回复
    热议问题