jQuery 简单的jquery总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10563541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple jquery sum
提问by Danish Adeel
I have unknown number of input fields, having class "add" I just wants to sum these with jquery, dont know where I am wrong.
我有未知数量的输入字段,有类“添加”我只想用 jquery 总结这些,不知道我错在哪里。
<input name="add" class="add" type="text">
<input name="add" class="add" type="text">
<input name="add" class="add" type="text">
<input name="add" class="add" type="text">
<input type="button" value="" onClick="add()" />
`
`
function add(){
val = 0;
$(".add").each(function() {
str = (parseInt(this.value))
sum=str+str
});
alert (sum)
}
`
`
回答by Alnitak
You're never actually adding stuff into sum
:
你从来没有真正添加东西到sum
:
function add() {
var sum = 0;
$(".add").each(function() {
sum += +this.value;
});
return sum; // an add function shouldn't really "alert"
}
If the intention is to only support whole numbers, use parseInt(this.value, 10)
[note the radix parameter] instead of +this.value
:
如果打算仅支持整数,请使用parseInt(this.value, 10)
[注意基数参数] 而不是+this.value
:
function add() {
var sum = 0;
$(".add").each(function() {
var str = this.value.trim(); // .trim() may need a shim
if (str) { // don't send blank values to `parseInt`
sum += parseInt(str, 10);
}
});
return sum;
}
回答by benqus
function add(){
var sum = 0;
$(".add").each(function() {
var val = parseInt($(this).val(), 10)
sum += (!isNaN(val) ? val : 0);
});
alert(sum);
}
Edit: Sharp eyes, got the parenthesis... =) And the space.
编辑:锐利的眼睛,得到了括号...... =) 还有空间。
回答by mark.monteiro
If you don't need to support IE8 then you can use the native Javascript Array.prototype.reduce()
method. You will need to convert your JQuery object into an array first:
如果您不需要支持 IE8,那么您可以使用原生 JavascriptArray.prototype.reduce()
方法。您需要先将 JQuery 对象转换为数组:
function add() {
return $('.add').toArray().reduce(function(sum,element) {
return sum + Number(element.value);
}, 0);
}
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
参考:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce