开发者

Create nested div from json result

I recieve from an AJAX call data which has an architecture like

data
[0] =>
      "date" => "blah"
      "location" => "blah"
      ...
[1] =>
      "date" => "moreblah"...................

I would like to create nested divs for each of the elements in data like this 开发者_C百科 blah blah ... moreblah ... .....

I have:

for(var i in data){
    $("<div class='event_item'>").appendTo("#thelist");
    //make div class "date" with event.date inside
    $("<div class='date'>" + data[i].date + "</div>").appendTo("#thelist");
    //make div class "location" with event.location inside
    $("<div class='location'>" + data[i].location + "</div>").appendTo("#thelist");
    //make div class "descrip" with event.descrip inside
    $("<div class='descrip'>" + data[i].description + "</div>").appendTo("#thelist");
    //make div class "detail" with event.extra inside
    $("<div class='detail'>" + data[i].extra + "</div>").appendTo("#thelist");
    $("</div>").appendTo("#thelist");
}

this doesn't work.. what i really want to do is append it to the newly created "event" div... not the list... how can i do that?

Thanks!!!


Try something like this: also, make sure use always create complete html tags. You're adding dom elements, not printing something to the document, Thus: do's: $('<div></div>);. Dont's: $('</div>').

for(var i in data){

    var event = $("<div class='event_item'></div>");
    //make div class "date" with event.date inside
    $("<div class='date'>" + data[i].date + "</div>").appendTo(event);
    //make div class "location" with event.location inside
    $("<div class='location'>" + data[i].location + "</div>").appendTo(event);
    //make div class "descrip" with event.descrip inside
    $("<div class='descrip'>" + data[i].description + "</div>").appendTo(event);
    //make div class "detail" with event.extra inside
    $("<div class='detail'>" + data[i].extra + "</div>").appendTo(event);
    console.log(event);
    $(event).appendTo('#theList');
}

To play around with it, see the jsfiddle: http://jsfiddle.net/Fn3Fm/


  1. Create the new div.
  2. Append it to the list.

    for(var i in data){
        var event = $("<div class='event_item'></div>");
        event.append("<div class='date'>" + data[i].date + "</div>");
        // ... other stuff for the event div
    
        $("#thelist").append(event);
    }
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜