标签:
用JS做一个简单的网页计算器如上图所示,只进行简单的加减乘除运算
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计数器</title>
</head>
<body>
<input type="text" name="text" id="pre" onblur="validate(this.value);">
<select id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" name="text" id="next" onblur="validate(this.value);">
<span>=</span>
<input type="text" id="result" readonly="true">
<input type="button" id="btn" value="提交" onclick="calculator();">
<script>
function validate(str){
var reg = /^\d+$/;
if (!reg.test(str)) {
alert("请输入数字");
}
}
function calculator(){
var pre=document.getElementById("pre").value;
var next=document.getElementById("next").value;
var opra=document.getElementById("operator").value;
var result=0;
switch(opra) {
case "+":
result=parseInt(pre)+parseInt(next);
break;
case "-":
result=parseInt(pre)-parseInt(next);
break;
case "*":
result=parseInt(pre)*parseInt(next);
break;
case "/":
if(parseInt(next)!=0){
result=parseInt(pre)/parseInt(next);
}
else{
alert("除数不能为0");
return;
}
break;
default:
break;
}
document.getElementById("result").value=result;
}
</script>
</body>
</html>
标签:
原文地址:http://www.cnblogs.com/yujiangong/p/5779985.html