我试图在多个部分中找到输入值的总和.我把我的代码放到了下面.
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>
Run Code Online (Sandbox Code Playgroud)
jQuery:
$('.section').each(function(){
var totalPoints = 0;
$(this).find('input').each(function(){
totalPoints += $(this).val();
});
alert(totalPoints);
});
Run Code Online (Sandbox Code Playgroud)
请注意,这是我实际使用的代码的简化版本.所以我希望这可以提醒2个值(每个部分的总和):8然后6.相反,我只是获取所有值的字符串.所以第一部分警告0143.
有什么想法我如何获得累积总和而不是字符串?
Roy*_*mir 35
你正在做"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);
});
Run Code Online (Sandbox Code Playgroud)
赶上?为什么?
回答:如果你不这样做,你应该总是使用基数原因,前导零是八进制!
parseInt("010") //8 ( ff)
parseInt("010") //10 ( chrome)
parseInt("010",10) //10 ( ff)
parseInt("010",10) //10 ( chrome)
Run Code Online (Sandbox Code Playgroud)
反正你懂这个意思.供应基数!
最终解决方案(使用.each( function(index, Element) )
)
$('.section').each(function(){
var totalPoints = 0;
$(this).find('input').each(function(i,n){
totalPoints += parseInt($(n).val(),10);
});
alert(totalPoints);
});
Run Code Online (Sandbox Code Playgroud)
小智 6
var totalPoints = 0;
$('.section input').each(function(){
totalPoints = parseFloat($(this).val()) + totalPoints;
});
alert(totalPoints);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
51685 次 |
最近记录: |