我遇到了这个功能的问题。当我将对象推入数组时,没关系,但是当我检索存储的对象时,我在每个对象中都有相同的值。
function saveDetails() {
var details = [];
var productDetails = {};
var id = $('#ddlDeliveryBoy option:selected').val();
var count = $('#tbCustomer tbody tr').length;
for (var index = 0; index < count; index++) {
var tr = $('#tbCustomer tbody tr')[index];
var countTD = $(tr).children('td').length - 4;
for (var j = 3; j < (countTD + 4); j++) {
var td = $(tr).children('td')[j];
var txt = $(td).find('input[type="text"]');
if ($.isNumeric(txt.val())) {
productDetails.CustomerID = $(tr).data('id');
productDetails.ProductID = $(td).data('id');
productDetails.Quantity = parseFloat(txt.val()).toFixed(2);
details.push(productDetails);
}
}
}
console.log(details);
}
答案 0 :(得分:2)
你需要在if循环中移动 productDetails 初始化。 这是代码。
function saveDetails() {
var details = [];
var id = $('#ddlDeliveryBoy option:selected').val();
var count = $('#tbCustomer tbody tr').length;
for (var index = 0; index < count; index++) {
var tr = $('#tbCustomer tbody tr')[index];
var countTD = $(tr).children('td').length - 4;
for (var j = 3; j < (countTD + 4); j++) {
var td = $(tr).children('td')[j];
var txt = $(td).find('input[type="text"]');
if ($.isNumeric(txt.val())) {
let productDetails = {};
productDetails.CustomerID = $(tr).data('id');
productDetails.ProductID = $(td).data('id');
productDetails.Quantity = parseFloat(txt.val()).toFixed(2);
details.push(productDetails);
}
}
}
console.log(details);
}