问题的一部分是丢失的#total
元素(假定您正在尝试更改其值,假定是input
)。
但是从功能&元素的名称来判断,我假设你还希望total
增加,只要你点击一个无线电输入。对于这一点,你需要你的total
变量移到功能之外,这将创建一个closure(即你的total
变量将在调用之间保持其价值totalIt()
)。请注意,我添加了一个break
,因为一旦找到您选中的其他收音机箱,就不需要继续检查。
// Note this is outside the function
var total = 0;
function totalIt() {
var input = document.getElementsByName("size");
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
// exit loop once checked radio is found
break;
}
}
document.getElementById("total").value = "£" + total.toFixed(2);
}
Small (£3.99)<input type="radio" name="size" id="s1" value="3.99" onclick="totalIt()"/>
Medium (£4.99)<input type="radio" name="size" id="s2" value="4.99" onclick="totalIt()"/>
Large (£5.99)<input type="radio" name="size" id="s3" value="5.99" onclick="totalIt()"/>
<div>
Total <input type="text" readonly id="total" value="£0.00"/>
</div>
或者,你可以阅读&从input#total
元素分析的价值,万一有原因,为什么你不能在这里使用封闭。
function totalIt() {
var input = document.getElementsByName("size");
var total = parseFloat(document.getElementById("total").value.slice(1));
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
// exit loop once checked radio is found
break;
}
}
document.getElementById("total").value = "£" + total.toFixed(2);
}
Small (£3.99)<input type="radio" name="size" id="s1" value="3.99" onclick="totalIt()"/>
Medium (£4.99)<input type="radio" name="size" id="s2" value="4.99" onclick="totalIt()"/>
Large (£5.99)<input type="radio" name="size" id="s3" value="5.99" onclick="totalIt()"/>
<div>
Total <input type="text" readonly id="total" value="£0.00"/>
</div>
在上述两种情况下,你实际上并不需要无线电输入或一个循环,因为无线电基本上像个按钮;你可以用普通的按钮替换它们,并用一个参数来调用totalIt()
(它可以大大简化),用于增加的数量。
如果你实际上是一个运行总计不感兴趣,只是想在任何给定的时间显示总的检查项目,那么你真的找一个复选框输入,然后你不必担心关于关闭,解析或休息。
function totalIt() {
var input = document.getElementsByName("size");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "£" + total.toFixed(2);
}
Small (£3.99)<input type="checkbox" name="size" id="s1" value="3.99" onclick="totalIt()"/>
Medium (£4.99)<input type="checkbox" name="size" id="s2" value="4.99" onclick="totalIt()"/>
Large (£5.99)<input type="checkbox" name="size" id="s3" value="5.99" onclick="totalIt()"/>
<div>
Total <input type="text" readonly id="total" value="£0.00"/>
</div>
有在你的HTML没有'#total'元素。 –
同意缺少'#total'是一个问题,OP应该包含它或解释为什么它不在片段中;但我不认为这是唯一的问题。根据你想要完成的事情来看看我的答案。 – tavnab
我忘了包括它。我现在已将它添加到帖子中! –