JavaScript:实现简易计算功能
body部分
<input type="text" id="num1"/>
<select id="options">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" id="num2"/>
<button onclick="compute()">=</button>
<p id = "result"></p>
实现计算
<script>
function compute(){
var num1 = document.getElementById("num1").value;//获取第一个输入框的值
var num2 = document.getElementById("num2").value;//获取第二个输入框的值
var selection = document.getElementById("options").value;//获取选择框的值
var result = 0;//设置结果的值
if(selection == "+"){
result = parseInt(num1)+ parseInt(num2);
console.log(result);
}
if(selection == "-"){
result = parseInt(num1)- parseInt(num2);
console.log(result);
}
if(selection == "*"){
result = parseInt(num1)* parseInt(num2);
console.log(result);
}
if(selection == "/"){
result = parseInt(num1)/ parseInt(num2);
console.log(result);
}
document.getElementById("result").innerHTML = result;
}
</script>
完整代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>简易计算器</title>
</head>
<body>
<input type="text" id="num1"/>
<select id="options">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" id="num2"/>
<button onclick="compute()">=</button>
<p id = "result"></p>
<script>
function compute(){
var num1 = document.getElementById("num1").value;//获取第一个输入框的值
var num2 = document.getElementById("num2").value;//获取第二个输入框的值
var selection = document.getElementById("options").value;//获取选择框的值
var result = 0;//设置结果的值
if(selection == "+"){
result = parseInt(num1)+ parseInt(num2);
console.log(result);
}
if(selection == "-"){
result = parseInt(num1)- parseInt(num2);
console.log(result);
}
if(selection == "*"){
result = parseInt(num1)* parseInt(num2);
console.log(result);
}
if(selection == "/"){
result = parseInt(num1)/ parseInt(num2);
console.log(result);
}
document.getElementById("result").innerHTML = result;
}
</script>
</body>
</html>