gpt4 book ai didi

javascript - 为什么我的 in for each 循环只添加最后一个元素?

转载 作者:行者123 更新时间:2023-11-30 14:19:56 25 4
gpt4 key购买 nike

我最近在使用 jQuery,我有一个问题,我想为两个产品添加一个值,每个产品都有自己的值(value)。但目前它只将最后一个元素添加到两者中。这是如何解决的?

我的jquery:

$('.count').on('blur', function getTotalPrice(){
var name = $(this).parent().parent().find('.name').html();
var count = $(this).val();

$.ajax({
type: "GET",
url: "cart",
data: "name=" + name + "&count=" + count,
success: function(data){

$("#totalPrice").text("Total price: " + data['totalPrice'].toFixed(2)).wrap("<h4></h4>");
$("#productCount").text("(" + data['productCount'] + ")");
console.log(data);

$.each(data['totalPriceForOne'], function(key, value) {
$(".totalPriceForOne").text((key * value).toFixed(2)); //field where i add
});
},
dataType: "json"
});
});

这是我从 jsnon 得到的:

> productCount: 2 
> totalPrice: 910
> totalPriceForOne: {100.00: 1, 810.00: 1}

我需要将 totalPriceForOne 添加到每个元素。如何实现?

最佳答案

如果有多个 .totalPriceForOne 元素,并且每个元素都需要从对象中获取不同的总数,则需要对其进行索引。

var index = 0;
$.each(data['totalPriceForOne'], function(key, value) {
$(".totalPriceForOne").eq(index++).text((key * value).toFixed(2)); //field where i add
});

关于javascript - 为什么我的 in for each 循环只添加最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52933408/

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