gpt4 book ai didi

javascript - AngularJS 和 JQuery $.each() 函数只返回最后一个循环值

转载 作者:搜寻专家 更新时间:2023-11-01 04:22:44 24 4
gpt4 key购买 nike

我一直在我的项目中使用 AngularJS 和集成的 JQuery 库。

我正在使用 JQuery 的 $.each() 函数循环访问我的类。我想从中创建一个对象数组,就像下面的格式一样:

[
{"invoice_no":"value1", "brand":"value2", "model":"value3"},
{"invoice_no":"value1", "brand":"value2", "model":"value3"},
{"invoice_no":"value1", "brand":"value2", "model":"value3"},
{"invoice_no":"value1", "brand":"value2", "model":"value3"},
{"invoice_no":"value1", "brand":"value2", "model":"value3"},
]

HTML

<div class="panels">
<input class="form-control" name="invoice_no">
<input class="form-control" name="brand">
<input class="form-control" name="model">
</div>
<div class="panels">
<input class="form-control" name="invoice_no">
<input class="form-control" name="brand">
<input class="form-control" name="model">
</div>
<div class="panels">
<input class="form-control" name="invoice_no">
<input class="form-control" name="brand">
<input class="form-control" name="model">
</div>
<div class="panels">
<input class="form-control" name="invoice_no">
<input class="form-control" name="brand">
<input class="form-control" name="model">
</div>
<div class="panels">
<input class="form-control" name="invoice_no">
<input class="form-control" name="brand">
<input class="form-control" name="model">
</div>

JS Controller

$scope.saveData = function(){
var arrayOFProducts = [];
var object = {};

angular.element('.panels').each(function(){
$(this).find('.form-control').each(function(){
var key = $(this).attr('name');
var value = $(this).val();
object [key] = value;
});
arrayOFProducts.push(object);
});

console.log(arrayOFProducts);

}

这里的主要问题是我为数组中的所有 json 对象获取了相同的值。似乎只有最后一个输入值被创建为对象,并将其推送到数组 5 次。

最佳答案

问题是因为您需要在外循环的每次迭代后将追加的对象重置回空状态。试试这个:

$scope.saveData = function() {
var arrayOFProducts = [];

angular.element('.panels').each(function() {
var obj = {}; // note this moved to here

$(this).find('.form-control').each(function() {
var key = $(this).attr('name');
var value = this.value;
obj[key] = value;
});
arrayOFProducts.push(object);
});

console.log(arrayOFProducts);
}

关于javascript - AngularJS 和 JQuery $.each() 函数只返回最后一个循环值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41261631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com