我想添加所有单击的单选按钮的值,但我得到的数字不正确。
<div id="config">
<input type="radio" name="brand" id="dell" value="Dell $1500"> Dell
<input type="radio" name="brand" id="mackbookpro" value="MacbookPro $3000"> Macbook Pro
<input type="radio" name="brand" id="asus" value="Asus $2000"> Asus
<input type="radio" name="ram" id="4gb" value="4 Gb $60"> 4 GB RAM
<input type="radio" name="ram" id="8gb" value="4 Gb $90"> 8 GB RAM
<input type="radio" name="ram" id="16gb" value="4 Gb $125"> 16 GB RAM
<input type="radio" name="storage" id="250gb" value="250 Gb $100"> 250 Gb Storage
<input type="radio" name="storage" id="500gb" value="500 Gb $200"> 500 Gb Storage
<input type="radio" name="storage" id="900gb" value="900 Gb $300"> 900 Gb Storage
</div>
<div id="show">0</div>
jQuery 看起来像这样
var displayPrice = document.getElementById('show');
$("#config input[type=radio]").click(function() {
var total = 0;
$("#config input[type=radio]:checked").each(function() {
var checked = $(this).val();
var checkNum = checked.split('$')[1];
total += parseFloat(checkNum);
});
displayPrice.innerHTML = total;
});
我得到的数学结果加起来不正确。我做错了什么吗?
最佳答案
我稍微调整了一下,似乎工作正常:
$("#config").click("input[type=radio]",function() {
var total = 0;
$(this).parent().find('input[type=radio]').each(function() {
var self = this;
if(self.checked){
total += parseFloat(self.value.split('$')[1]);
}
});
alert(total);
});
关于javascript - 如何通过使用正则表达式更改值来获取单选按钮值的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25673499/