为什么jquery.each执行两次?

时间:2013-01-18 02:21:27

标签: javascript jquery each

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/

3 个答案:

答案 0 :(得分: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/

答案 1 :(得分: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项目中。

答案 2 :(得分: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);
});