在同一个类中添加值并返回总和
16lz
2021-01-22
Hello people here is my code below...
你好,这里的人是我的代码......
var total = 0;
var find_total;
function total_val(find_total){
$(find_total).each(function() {
total += parseInt($(this).text());
return total;
});
}
Iam calling this function...
我叫这个功能......
$('#total_price').val(total_val('.price'));
#total_price
and .price
keeps changing for different div ids and class
... return total;
does not work, any ways to fix this??
#total_price和.price不断更改不同的div id和class ... return total;不起作用,任何解决方法?
2 个解决方案
#1
1
You are returning the total value inside the .each()
function, it would not return anything while we expecting a value from the function total_val()
,
你在.each()函数中返回总值,当我们期望函数total_val()的值时,它不会返回任何内容,
Try,
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;
}
or you could use .reduce()
to make your code simple.
或者您可以使用.reduce()来简化代码。
function total_val(find_total){
return $(find_total).map(function() {
return parseInt($(this).text());
}).get().reduce(function(a,b){
return a+b;
});
}
Even simpler,
function total_val(find_total){
return $(find_total).get().reduce(function(a,b){
return a+ parseInt($(b).text(),10);
},0);
}
更多相关文章
- 我无法理解为什么我的代码中的单击选择文本
- js字符串与html代码互相转换时怪想法:自己解析js字符串成普通字
- 解决FCKEditor编辑器在浏览器返回时显示html源代码的问题
- 如何让这段插入的innerHTML 里动态赋予的函数跑起来!
- 高分求:如何解析IdHTTP获得的http代码?用mshttp的IHTMLDocument2可
- 韩顺平_轻松搞定网页设计(html+css+javascript)_第19讲_js运行原
- jQuery animate()函数没有动画
- HTML显示日期时间代码 - [js 特效代码]
- 解决html代码中插入的图片在浏览器中不显示的办法