使用 a+=
和一个简单的三元运算符:
var total = 0;
total += document.getElementById('cb1').checked ? parseInt(document.getElementById('cb1').value, 10) : 0;
total += document.getElementById('cb2').checked ? parseInt(document.getElementById('cb2').value, 10) : 0;
total += document.getElementById('cb3').checked ? parseInt(document.getElementById('cb3').value, 10) : 0;
alert(total);
我应该透露这与以下内容相同:
var total2 = 0;
if (document.getElementById('cb1').checked) total2 += parseInt(document.getElementById('cb1').value, 10);
if (document.getElementById('cb2').checked) total2 += parseInt(document.getElementById('cb2').value, 10);
if (document.getElementById('cb3').checked) total2 += parseInt(document.getElementById('cb3').value, 10);
alert(total2);
示例 HTML:
<input id="cb1" type="checkbox" value="341" checked />
<input id="cb2" type="checkbox" value="242" />
<input id="cb3" type="checkbox" value="345" checked />