2017-08-30 90 views
0

我正在迭代动态生成的div,其中包含一个表。当我遍历行时​​,假设我有两行,我得到两个结果。但问题是两个结果都包含最后一行表的值。这里是我的代码:迭代表的行

$(this) 
    .children('.js-charge-data') 
    .children('.js-charging-line-wrapper') 
    .find('.js-chargeline-tbody') 
    .children('tr') 
    .each(function() { 
    chargingLineJSON['chargingType'] = 'IoT'; 
    chargingLineJSON['chargeCategoryName'] = $(this).find('.js-charging-category').val().trim(); 
    chargingLineJSON['subCategoryName'] = $(this).find('.js-charging-sub-category').val().trim(); 
    chargingLineJSON['backEndProductName'] = $(this).find('.js-charging-sub-category').children(':selected').data('backend_product_name'); 
    chargingLineJSON['shipToAddressId'] = '123'; 
    chargingLineJSON['chargePerUnit'] = $(this).find('.js-unit-charge').val().trim(); 

    chargeLineListJSON['chargingLine'] = chargingLineJSON; 
    chargingLineJSONArray.push(chargeLineListJSON); 
    }); 

请让我知道我在做什么错误?

+3

请包括所有相关的代码(html) –

回答

2

您正在推动同一对象chargingLineJSON到阵列,在.each()

.each(function() { 
    //Create a new object 
    var chargingLineJSON = {}; 
    //Your code 
    chargingLineJSONArray.push(chargeLineListJSON); 
}); 

作为每@Rajesh评论

对象使用参考复制创建新的对象。因此,在第二次迭代中,当您将值设置为对象的属性时,您将覆盖内存位置处的值而不是位于locat变量中。因此,相同的值

+1

感谢您的信任。 :-) – Rajesh

+0

@Satpal谢谢。这是问题。 –

+0

@Rajesh,我打算解释,但你评论因此.... – Satpal

1

如在@Satpalanswer中评论和记入的,问题是由于将对象复制为参考。

虽然为了减少数据的重复,但并未在我的回答中重复评论。

你可以使用这样的东西。

$(this) 
    .find('.js-charge-data .js-charging-line-wrapper .js-chargeline-tbody tr') 
    .each(function() { 
    let category = $(this).find('.js-charging-category'); 
    let subCategory = $(this).find('.js-charging-sub-category'); 
    let selectedSubCategory = $(this).find('.js-charging-sub-category :selected'); 
    let unitCharge = $(this).find('.js-unit-charge'); 

    chargingLineJSONArray.push({ 
     chargingType: 'IoT', 
     shipToAddressId: '123' 
     chargeCategoryName: category.val().trim(), 
     subCategoryName: subCategory.val().trim(), 
     backEndProductName: selectedSubCategory.data('backend_product_name'), 
     chargePerUnit: unitCharge.val().trim() 
    }); 

    // Not sure what this line is about? 
    // You are saving reference to self in a property. 
    // chargeLineListJSON['chargingLine'] = chargingLineJSON; 
    }); 

注:我没有测试代码标记丢失。