JavaScript:实现简易计算功能

该博客展示了一个使用JavaScript编写的简易计算器的实现。通过HTML和JavaScript交互,实现了加、减、乘、除四种基本运算。用户可以在输入框中输入数字,选择运算符,点击等号按钮,结果显示在页面上。
摘要由CSDN通过智能技术生成

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值