JSFiddle在这里:http://jsfiddle.net/xgTt2/3/
我在$.each
内嵌套了一个$.each
,但我不确定为什么第二个$.each
运行两次。有任何想法吗?
var serverResponse = [{"Id":"aaa","OrderItems":[{"Id":1,"Description":"Salad"},{"Id":2,"Description":"Pizza"}]},{"Id":"bbb","OrderItems":[{"Id":3,"Description":"Salad"},{"Id":4,"Description":"Pizza"}]}];
$.each(serverResponse, function (index) {
var pos = serverResponse[index];
$('#placeholder').append('<p>' + pos.Id + '</p>')
$.each(pos.OrderItems, function (index) {
$('.orderitem').append('<p>' + this.Id +
' ' + this.Description + '</p>')
});
});
上面的javascript产生以下输出:
aaa
1 Salad
2 Pizza
3 Salad
4 Pizza
bbb
3 Salad
4 Pizza
我要这个:
aaa
1 Salad
2 Pizza
bbb
3 Salad
4 Pizza
知道我在做什么错吗?这是问题的可行示例:http://jsfiddle.net/xgTt2/3/
最佳答案
在结尾处,您有两个元素为orderitem
类。使用$('.orderitem').append()
将同时添加到它们两个。
相反,您想追加到您创建的最后一个元素。
var $order_item = $('<p class="orderitem">' + pos.Id + '</p>');
$('#placeholder').append($order_item);
$.each(pos.OrderItems, function (index) {
$order_item.append('<p>' + this.Id +
' ' + this.Description + '</p>');
});
http://jsfiddle.net/xgTt2/4/