目录
代码运算效果
代码
<!DOCTYPE html
>
<html
>
<head
>
<meta charset
="utf-8" />
<title
>简易计算器
</title
>
<style type
="text/css">
body
{
text
-align
: center
;
}
</style
>
</head
>
<body
>
<h1
>简易计算器
</h1
>
<input type
="text" id
="one" placeholder
="请输入第一个数" /><br
/>
<select id
="choice">
<option value
="default">请选择运算符
</option
>
<option value
="+">+</option
>
<option value
="-">-</option
>
<option value
="*">*</option
>
<option value
="/">/</option
>
</select
><br
/>
<input type
="text" id
="two" placeholder
="请输入第二个数" /><br
/>
<input type
="button" value
="计算" onclick
="count()" /><br
/>
<span
>计算结果
:</span
><span id
="show"></span
>
<script type
="text/javascript">
function count() {
var num1
= document
.getElementById("one").value
;
var num2
= document
.getElementById("two").value
;
var choiceID
= document
.getElementById("choice");
var index
= choiceID
.selectedIndex
;
var choiceText
= choiceID
.options
[index
].value
;
var isNum
= isNaN(num1
) || isNaN(num2
);
var isAddition
= (choiceText
== "+" && !isNum
);
var isSubtraction
= (choiceText
== "-" && !isNum
);
var isMultiplication
= (choiceText
== "*" && !isNum
);
var isDivision
= (choiceText
== "/" && !isNum
);
var isChoice
= (choiceText
== "default");
if(isNum
) {
alert("请输入数字!");
} else if(isChoice
) {
alert("请选择运算符!");
} else if(isAddition
) {
var sum
= Number(num1
) + Number(num2
);
document
.getElementById("show").innerText
= sum
;
} else if(isSubtraction
) {
var sum
= Number(num1
) - Number(num2
);
document
.getElementById("show").innerText
= sum
;
} else if(isMultiplication
) {
var sum
= Number(num1
) * Number(num2
);
document
.getElementById("show").innerText
= sum
;
} else if(isDivision
) {
if(num2
== 0) {
alert("除数不能为0!");
} else {
var sum
= Number(num1
) / Number(num2
);
document
.getElementById("show").innerText
= sum
;
}
}
}
</script
>
</body
>
</html
>
运算效果
页面效果 没有选择运算符 输入内容不是数字 除数为0 加法 减法 乘法 除法
转载请注明原文地址: https://lol.8miu.com/read-11355.html