我正在尝试以JSON格式获取存储在表中的数据,但是当它使用.each来获取数据时,最新值一直在重复。
我已经显示了实际输出,该输出应该与表行中的数据不同
function getPackTableDetails() {
var packDetailsRow = [];
var tableRowCount = $('#addPackTable tr').length;
var returnJSONFormat = "";
$('#addPackTable tr').each(function(index) {
if(index != 0) {
var packDetailsObj = {};
($(this).find("td")).each(function(idx) {
switch(idx) {
case 0:
packDetailsObj.table_pack_name = $('#table_pack_name').val();
break;
case 1:
packDetailsObj.table_pack_type = $('#table_pack_type').val();
break;
case 2:
packDetailsObj.base_amount = $('#base_amount').val();
break;
case 3:
packDetailsObj.tax_amount = $('#tax_amount').val();
break;
case 4:
packDetailsObj.total_amount = $('#total_amount').val();
break;
}
});
packDetailsRow.push(packDetailsObj);
}
});
// console.log(JSON.stringify(packDetailsRow));
return packDetailsRow;
}
当我使用输入类型文本时,我使用值来存储数据,然后使其检索到以下jquery代码
Output:
{
"pack_details": [
{
"table_pack_name": "Demo Pack Name5",
"table_pack_type": "Demo Pack Name5",
"base_amount": "200.00",
"tax_amount": "0.00",
"total_amount": "200.00"
},
{
"table_pack_name": "Demo Pack Name5",
"table_pack_type": "Demo Pack Name5",
"base_amount": "200.00",
"tax_amount": "0.00",
"total_amount": "200.00"
},
{
"table_pack_name": "Demo Pack Name5",
"table_pack_type": "Demo Pack Name5",
"base_amount": "200.00",
"tax_amount": "0.00",
"total_amount": "200.00"
}
]
}
实际输出:
{
"pack_details": [
{
"table_pack_name": "Demo Pack Name5",
"table_pack_type": "Demo Pack Name5",
"base_amount": "20.00",
"tax_amount": "10.00",
"total_amount": "30.00"
},
{
"table_pack_name": "Demo Pack Name6",
"table_pack_type": "Demo Pack Name6",
"base_amount": "200.00",
"tax_amount": "0.00",
"total_amount": "200.00"
},
{
"table_pack_name": "Demo Pack Name7",
"table_pack_type": "Demo Pack Name7",
"base_amount": "400.00",
"tax_amount": "40.00",
"total_amount": "440.00"
}
]
}
答案 0 :(得分:0)
因为您每次迭代都分配相同的值
switch(idx) {
case 0:
packDetailsObj.table_pack_name = $('#table_pack_name').val();
break;
case 1:
packDetailsObj.table_pack_type = $('#table_pack_type').val();
break;
case 2:
packDetailsObj.base_amount = $('#base_amount').val();
break;
case 3:
packDetailsObj.tax_amount = $('#tax_amount').val();
break;
case 4:
packDetailsObj.total_amount = $('#total_amount').val();
break;
}
答案 1 :(得分:0)
应遵循的几件事是id应该是元素唯一的,并且两个元素都不应具有相同的id。检查this以进一步阅读。您可以改为使用name属性读取值,如下所示。
$('#addPackTable tr').each(function (index) {
if (index != 0) {
var packDetailsObj = {};
($(this).find("td")).each(function (idx) {
switch (idx) {
case 0:
packDetailsObj.table_pack_name = $(this).find('[name="table_pack_name"]').val();
break;
case 1:
packDetailsObj.table_pack_type = $(this).find('[name="table_pack_type"]').val();
break;
case 2:
packDetailsObj.base_amount = $(this).find('[name="base_amount"]').val();
break;
case 3:
packDetailsObj.tax_amount = $(this).find('[name="tax_amount"]').val();
break;
case 4:
packDetailsObj.total_amount = $(this).find('[name="total_amount"]').val();
break;
}
});
packDetailsRow.push(packDetailsObj);
}