我尝试在多个部分中查找输入值的总和。到目前为止,我已经把代码放在下面了。
HTML:
<div class="section">
<input type="radio" name="q1" value="2"/>
<input type="radio" name="q2" value="0"/>
<input type="radio" name="q3" value="1"/>
<input type="radio" name="q4" value="3"/>
</div>jQuery:
$('.section').each(function(){
var totalPoints = 0;
$(this).find('input').each(function(){
totalPoints += $(this).val();
});
alert(totalPoints);
});请注意,这是我实际使用的代码的简化版本。所以我想要警告2个值(每个部分的总和):8,然后是6。我只是得到了一个包含所有值的字符串。所以第一部分的警报是0143。
你知道我如何得到一个累积和而不是一个字符串吗?
发布于 2013-01-03 23:35:54
你正在做"1"+"1“,并且期望它是2( int)
事实并非如此。
一个非常快速(但不完全正确)的解决方案是:
$('.section').each(function(){
var totalPoints = 0;
$(this).find('input').each(function(){
totalPoints += parseInt($(this).val()); //<==== a catch in here !! read below
});
alert(totalPoints);
});接住?为什么?
答:你应该总是使用基数,因为如果你不这样做,前导零就是八进制的!
parseInt("010") //8 ( ff)
parseInt("010") //10 ( chrome)
parseInt("010",10) //10 ( ff)
parseInt("010",10) //10 ( chrome)好吧..。你明白了吧。提供基数!
编辑
最终解决方案(使用.each( function(index, Element) ))
$('.section').each(function(){
var totalPoints = 0;
$(this).find('input').each(function(i,n){
totalPoints += parseInt($(n).val(),10);
});
alert(totalPoints);
});发布于 2013-01-03 23:44:43
var totalPoints = 0;
$('.section input').each(function(){
totalPoints = parseFloat($(this).val()) + totalPoints;
});
alert(totalPoints);发布于 2013-01-03 23:35:45
totalPoints += parseInt($(this).val(), 10);https://stackoverflow.com/questions/14142011
复制相似问题