gpt4 book ai didi

javascript - 在同一个类中添加值并返回总和

转载 作者:可可西里 更新时间:2023-11-01 14:48:43 24 4
gpt4 key购买 nike

大家好,下面是我的代码...

var total = 0;
var find_total;
function total_val(find_total){

$(find_total).each(function() {
total += parseInt($(this).text());
return total;
});

}

我正在调用这个函数...

$('#total_price').val(total_val('.price'));

#total_price.price不同的 div ids 和 class 而不断变化 ... return total;不起作用,有什么办法可以解决这个问题??

最佳答案

您在 .each() 函数中返回总值,当我们期望函数 total_val() 返回值时,它不会返回任何东西,

尝试,

function total_val(find_total){ 
var total = 0; //remove the global variable total and use this.
$(find_total).each(function() {
total += parseInt($(this).text());
});
return total;
}

或者您可以使用 .reduce() 来简化您的代码。

function total_val(find_total){ 
return $(find_total).map(function() {
return parseInt($(this).text());
}).get().reduce(function(a,b){
return a+b;
});
}

更简单,

function total_val(find_total){ 
return $(find_total).get().reduce(function(a,b){
return a+ parseInt($(b).text(),10);
},0);
}

关于javascript - 在同一个类中添加值并返回总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24319956/

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