简单的JavaScript计算器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Yonggie/article/details/89669848

带有enter键出结果,

可以直接复制粘贴。

<html>
	<head>
	</head>
		<title> calculator</title>
		<script src="jquery-3.3.1.min.js"> </script>
		<style>
			#container{
				margin:0 auto;
				text-align:center;
			}
			input{
				width:100px;
			}
		</style>
	<body>
		<center><h1>xxx计算器,用了都说好!</h1></center>
		<div id="container">
			<input type=text id="first"/>
			<select id="op">
				<option>+</option>
				<option>-</option>
				<option>*</option>
				<option>/</option>
			</select>
			<input type=text id="second"/>
			<span> = </span>
			<span id="result"> </span>
			<br><br><br>
			<button id="do" onclick="cal()">计算</button>
		</div>
		<script>
		//1.2+2.4===3.5999999996
			function cal(){
				var first = parseFloat($("#first").val());
				console.log(first);
				var second=parseFloat($("#second").val());
				console.log(second);
				var op=$("#op").val();
				if(isNaN(first)||isNaN(second)) alert("input is not a number! please re-input!");
				else {
					if(op==='+') $('#result').html(first+second);
					else if(op==='-')$('#result').html(first-second);
					else if(op==='/')$('#result').html(first/second);
					else if(op==='*')$('#result').html(first*second);
				}
			}
			$(function(){
				document.onkeydown=(function(event){
					var ev=document.all?window.event:event;
					if(ev.keyCode==13) cal();
				});
			});
			
			
		</script>
	</body>
</html>

猜你喜欢

转载自blog.csdn.net/Yonggie/article/details/89669848