Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我的in for each循环只添加最后一个元素?_Javascript_Jquery_Ajax - Fatal编程技术网

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

Javascript 为什么我的in for each循环只添加最后一个元素?,javascript,jquery,ajax,Javascript,Jquery,Ajax,我最近在与jQuery合作,我有一个问题,我有两个产品,我想增加价值,每个产品都有自己的价值。但目前,它只为两者添加了最后一个元素。这是如何修复的 我的jquery: $('.count').on('blur', function getTotalPrice(){ var name = $(this).parent().parent().find('.name').html(); var count = $(this).val(); $.ajax({ t

我最近在与jQuery合作,我有一个问题,我有两个产品,我想增加价值,每个产品都有自己的价值。但目前,它只为两者添加了最后一个元素。这是如何修复的

我的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"
    });
});
我需要将totalPriceForOne添加到每个元素中。这是如何实现的?

方法
.text(argument)
用参数替换元素的文本内容

如果你用X替换它,然后马上用Y替换它,那么X就不会粘在一起了:它已经被替换了


在循环外创建字符串<代码>+=循环中的每个新值。最后用
text()
设置最终结果

或者读取循环中的现有值并附加到该值:

foo.text( foo.text() + new_text )

或者使用
append()
方法(警告:注意包含HTML的文本),而不是
text()

不确定,但我认为您的问题在于:

$(".totalPriceForOne").text((key * value).toFixed(2)); //field where i add 

事实上,在循环中,您将替换以前的值,而这不是您要查找的值。我建议您使用一些think unique(如
id
)而不是使用类选择器。

如果有多个
。TotalPrice for one
元素,并且每个元素都需要从对象获取不同的总计,则需要对其进行索引

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

请显示在每次循环迭代中更新每个
$(“.totalPriceForOne”)
元素的文本时所需的输出。我不知道你想要的输出是什么,但这显然是不正确的。
var index = 0;
$.each(data['totalPriceForOne'], function(key, value) {
    $(".totalPriceForOne").eq(index++).text((key * value).toFixed(2)); //field where i add      
});