我想在html和javascript上做一個簡單的計算器,但是當輸入2個數字時,結果就是NaN。 我正在使用谷歌瀏覽器。 我現在認爲這可能是我的HTML代碼有問題。 我只是開始使用HTML和JavaScript,所以請簡單回答一下。JavaScript計算器NaN
<script language="JavaScript">
function workOut() {
var num1 = (document.getElementById('num1').value)
var num2 = (document.getElementById('num2').value)
if(document.getElementById('operation').value=="plus")
{
var answer= Number(num1) + Number(num2);
alert(answer);
}
if(document.getElementById('operation').value=="minus")
{
var answer= num1 - num2;
alert(answer);
}
if(document.getElementById('operation').value=="multiply")
{
var answer= num1 * num2;
alert(answer);
}
if(document.getElementById('operation').value=="divide")
{
var answer= num1/num2;
alert(answer);
}
}
</script>
</head>
<body>
<h1>Calculator</h1>
<form name="calculatordata">
<table width="50%" border="1px dashed">
<tr>
<td id="num1">Number 1</td>
<td><input type="number" name="number1" /></td>
</tr>
<tr>
<select id="operation">
<option value="plus">+</option>
<option value="minus">-</option>
<option value="multiply">x</option>
<option value="divide">/</option>
</tr>
<tr>
<td id="num2">Number 2</td>
<td><input type="number" name="number2" /></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onClick="return workOut();"/></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
var num1 = Number((document.getElementById('num1')。value)); var num2 = Number((document.getElementById('num2')。value));.嘗試這個。您只是在添加的情況下解析數字 – Triode
您能發佈一個完整的代碼示例,包括您的HTML嗎? – j08691
因爲.value返回一個字符串,而不是一個數字.. –