<title>Calculator</title>
<script type="text/javascript">
function Calculate(){
var myWorker = document.getElementById('myOperation');
var numberOne= document.getElementById('firstNumber').value;
var numberTwo= document.getElementById('secondNumber').value;
if (myWorker = "+") {
var provideAnswer = (numberOne + numberTwo);
var finalAnswer= document.getElementById('myAnswer');
finalAnswer.innerHTML = provideAnswer;
}
else {
alert('Please use Addition Symbol Only')
}
}
</script>
<h1>CALCULATOR</h1>
<br/>
<h2>Enter the first number</h2>
<input type="number" id="firstNumber" />
<br/>
<br/>
<h2>Enter the Operation</h2>
<input type="text" id="myOperation" />
<br/>
<br/>
<h2>Enter the second number</h2>
<input type="number" id="secondNumber" />
<input type="submit" value="Answer Is" onclick="Calculate()"/>
<br/>
<br/>
<h1 id="myAnswer">Your ANSWER Will be REPLACED by THIS TEXT</h1>
答案 0 :(得分:0)
您需要首先将值解析为数字-最快,最简单的方法是使用一元+
运算符:
function Calculate() {
var myWorker = document.getElementById('myOperation');
var numberOne = +document.getElementById('firstNumber').value;
var numberTwo = +document.getElementById('secondNumber').value;
if (myWorker == "+") {
var provideAnswer = (numberOne + numberTwo);
var finalAnswer = document.getElementById('myAnswer');
finalAnswer.innerHTML = provideAnswer;
} else {
alert('Please use Addition Symbol Only')
}
}
<h1>CALCULATOR</h1>
<h2>Enter the first number</h2>
<input type="number" id="firstNumber" />
<h2>Enter the Operation</h2>
<input type="text" id="myOperation" />
<h2>Enter the second number</h2>
<input type="number" id="secondNumber" />
<input type="submit" value="Answer Is" onclick="Calculate()" />
<h1 id="myAnswer">Your ANSWER Will be REPLACED by THIS TEXT</h1>
(我对HTML标记进行了一些修改,以删除换行符)