JavaScript简单计算器
程序员文章站
2022-03-03 22:33:19
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>简单计算器</title>
</head>
<body>
<div>
<input type="text" id="num1" value="">
<select id="yunsuanfu">
<option value="请选择">请选择</option>
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
<option value="%">%</option>
</select>
<input type="text" id="num2" value="">
<button id="count">
计算
</button>
<p id="jieguo"></p>
</div>
</body>
<script>
var count = document.getElementById('count');
count.onclick = function(){
var num1 =document.getElementById('num1').value;
var num2 =document.getElementById('num2').value;
var yunsuanfu =document.getElementById('yunsuanfu').value
var re = /^[0-9]+.?[0-9]*/;
if (num1 =='' || num2 ==''){
document.getElementById('jieguo').innerHTML= '错误:计算不能为空'
}
else if(num2 == 0 && (yunsuanfu =='/' || yunsuanfu == '%')){
document.getElementById('jieguo').innerHTML= '错误:被除数不能为0'
}
else if(!re.test(num1) || !re.test(num2)){
document.getElementById('jieguo').innerHTML= '错误:只能填写数字进行计算'
}
else {
num1 = parseFloat(num1);
num2 = parseFloat(num2);
console.log(num1)
console.log(num2)
if(yunsuanfu == '请选择'){
document.getElementById('jieguo').innerHTML='请选择运算符';
}
if(yunsuanfu == '+'){
document.getElementById('jieguo').innerHTML=num1+'+'+num2+'='+(num1+num2);
}
if(yunsuanfu == '-'){
document.getElementById('jieguo').innerHTML=num1+'-'+num2+'='+(num1-num2);
}
if(yunsuanfu == '*'){
document.getElementById('jieguo').innerHTML=num1+'*'+num2+'='+(num1*num2);
}
if(yunsuanfu == '/'){
document.getElementById('jieguo').innerHTML=num1+'除'+num2+'='+(num1/num2);
}
if(yunsuanfu == '%'){
document.getElementById('jieguo').innerHTML=num1+'取余'+num2+'='+(num1%num2);
}
}
}
</script>
</html>
上一篇: echarts移动端的适配思路
下一篇: js学习-实现简单计算器