使用jQuery将JSON对象打印到html中

时间:2014-01-09 23:11:18

标签: javascript jquery html

我有一个看起来像这样的JSON对象:

var content = '[{"title":"John Apple","lastname":"Apple"},
{"title":"Kumar Patel","lastname":"Patel"},
{"title":"Michaela Quinn","lastname":"Quinn"},
{"title":"Peyton Manning","lastname":"Manning"},
{"title":"John Doe","lastname":"Doe"},
{"title":"Jane Lee","lastname":"Lee"},
{"title":"Dan McMan","lastname":"McMan"},
{"title":"Yu Win","lastname":"Win"}]';

我正在尝试使用jQuery对其进行编辑,以便在我的div标记中显示,其ID为content-view

这是我的jquery:

$.each(content, function(t, l){
  $('#view-content').appendTo('<div id = "' + l + '">' + t + '</div>');
});

由于某些原因,我的jsFiddle就在这里:http://jsfiddle.net/gAWTV/

结果只是空白。有没有人有任何想法?我很难过......

--- --- EDIT

我想做的是将所有内容输出到自己的div标签中,如下所示:

<div id="Apple">John Apple</div>
<div id="Patel">Kumar Patel</div>
<div id="Quinn">Michaela Quinn</div>
etc...

2 个答案:

答案 0 :(得分:4)

您的content是一个字符串,而不是一个对象数组。

首先需要将其存储为数组,因此请删除单引号。

var content = [{"title":"John Apple","lastname":"Apple"},
{"title":"Kumar Patel","lastname":"Patel"},
{"title":"Michaela Quinn","lastname":"Quinn"},
{"title":"Peyton Manning","lastname":"Manning"},
{"title":"John Doe","lastname":"Doe"},
{"title":"Jane Lee","lastname":"Lee"},
{"title":"Dan McMan","lastname":"McMan"},
{"title":"Yu Win","lastname":"Win"}];

除非有理由将其存储为字符串?然后你需要parse它。

var content_object = JSON.parse(content);

然后你就可以运行你的代码了。但是,我想你想要“stringify”你的JSON。如果是这种情况,您还需要将tl交换,因为l是对象。最后,您想要append,而不是appendTo。后者将主题附加到您指定的目标,而不是相反的方向(因此在您的情况下appendTo会将#view-content附加到您构建的div,这不起作用。)

$.each(content, function(t, l){
    $('#view-content').append('<div id = "' + t + '">' + JSON.stringify(l) + '</div>');
});

JSFiddle

最终评论,我会使用document fragments来构建您的列表,而不是将新div添加到每个循环中的现有div中,从而提高性能。

OP编辑后:

将最后一个片段更改为:

$.each(content, function(t, l){
    $('#view-content').append('<div id = "' + l.lastname + '">' + l.title + '</div>');
});

Updated JSFiddle

答案 1 :(得分:0)

试试这个:

 var content = [{"title":"John Apple","lastname":"Apple"},
 {"title":"Kumar Patel","lastname":"Patel"},
 {"title":"Michaela Quinn","lastname":"Quinn"},
 {"title":"Peyton Manning","lastname":"Manning"},
 {"title":"John Doe","lastname":"Doe"},
 {"title":"Jane Lee","lastname":"Lee"},
 {"title":"Dan McMan","lastname":"McMan"},
 {"title":"Yu Win","lastname":"Win"}];

$.each(content, function(t, l){

 $('<div/>',{
  id: l,
  text:t }).appendTo('#view-content');

});

<强> DEMO