大家好,下面是我的代码...
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/