Sen*_*uXo 5 html javascript syntax
我的代码是一个简单的函数,它检查按下了哪个单选按钮,并将该单选按钮的值添加到我的var input = 0;.但是,我知道我做错了,因为它有效,但输出错误.当其中一个if陈述为真时,而不是输入(0)现在等于它自己加上新的值getElementById("small").value,它打印出来010而不是现在10.
我知道在Java中有一个类似的约定,input += getElementById("small").value;但这似乎不起作用.因此,正如您在下面的示例中所看到的,我尝试了替代input = input + /*code*/;但仍然没有运气.
我是JavaScript的新手,但对Java非常熟悉.我想我在这里只是使用了错误的语法,但我所有的Google搜索都是破产.
function calculate()
{
var input = 0;
if (document.getElementById("small").checked)
{
input = input + document.getElementById("small").value;
}
else if (document.getElementById("medium").checked)
{
input = input + document.getElementById("medium").value;
}
else if (document.getElementById("large").checked)
{
input = input + document.getElementById("large").value;
}
else
{
alert("failed");
}
document.getElementById("outar").innerHTML = input;
}
Run Code Online (Sandbox Code Playgroud)
你正试图用字符串算术.您需要parseInt()在每个document.getElementById("....").value表达式周围使用,因为该.value属性是一个字符串.
例:
input += parseInt(document.getElementById("small").value);
Run Code Online (Sandbox Code Playgroud)