2

JSFiddle在这里:http: //jsfiddle.net/xgTt2/3/

我在 a 中有一个$.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/

4

3 回答 3

3

接近尾声时,您有两个带有 class 的元素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/

于 2013-01-18T02:29:33.543 回答
1

这是答案:

http://jsfiddle.net/7EmsX/

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];
    var $orderItem = $('<p class="orderitem">' + pos.Id + '</p>');
    $orderItem.appendTo('#placeholder');
    $.each(pos.OrderItems, function (index) {
        $orderItem.append('<p>' + this.Id + ' ' + this.Description + '</p>')
    });
});

选择.orderitem类时,会选择每个pos项目并将子项目插入其中。您只想将子项目插入当前pos项目。

于 2013-01-18T02:29:41.483 回答
0

在第二次循环运行中,$('.orderitem')选择您的所有<p class="orderitem"></p>

试试下面:

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];
  var orderitemHTML = '';
  orderitemHTML += '<p class="orderitem">' + pos.Id + '</p>';

  $.each(pos.OrderItems, function (index) {
    orderitemHTML += '<p>' + this.Id + ' ' + this.Description + '</p>';
  });
  $('#placeholder').append(orderitemHTML);
});
于 2013-01-18T02:30:21.753 回答