<html>
<head>
<script type="text/javascript">
	function jsq(op) {
		var a = parseFloat(document.getElementById("num1").value);
		var b = parseFloat(document.getElementById("num2").value);

		switch (op) {
		case "+":
			document.getElementById("ans").value = a + b;
			break;
		case "-":
			document.getElementById("ans").value = a - b;
			break;
		case "*":
			document.getElementById("ans").value = a * b;
			break;
		case "/":
			if (b == 0) {
				alert("除数不能为0");
			} else {
				document.getElementById("ans").value = Math.round((a / b) * 100) / 100;//保留两位小数
			}
		}
	}
</script>
<body>
	num1:
	<input type="text" id="num1">
	<br> num2:
	<input type="text" id="num2">
	<br> op:
	<input type="button" value="+" onClick="jsq('+')">
	<input type="button" value="-" onClick="jsq('-')">
	<input type="button" value="*" onClick="jsq('*')">
	<input type="button" value="/" onClick="jsq('/')">
	<br> ans:
	<input type="text" id="ans">
</body>
</head>
</html>

简单的switch case方法,仅供参考

更多推荐

JavaScript实现简单的四则运算