1.if-else if的练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>if-else if与switch的练习</title>
</head>
<body>
<input type="text" placeholder="请输入第1个数" id="txt1">
<select name="" id="select">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" placeholder="请输入第2个数" id="txt2">
<button id="btn">计算</button>
<input type="text" value="0.00" id="box">
</body>
<script>
// 获取5个页面元素
var txt1 = document.getElementById("txt1");
var txt2 = document.getElementById("txt2");
var select = document.getElementById("select")
var btn = document.getElementById("btn");
var box = document.getElementById("box");
//按钮的点击事件
btn.onclick = function () {
// 获取文本框的value值
var x = Number(txt1.value);
var y = Number(txt2.value);
var op = select.value; // 获取下拉列表的value值
if (op == "+") {
var s = (x + y).toFixed(2);
} else if (op == "-") {
var s = (x - y).toFixed(2);
} else if (op == "*") {
var s = (x * y).toFixed(2);
} else {
var s = (x / y).toFixed(2);
}
box.value = s; // 设置第三个文本框的value值
}
</script>
</html>
2.switch的练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>if-else if与switch的练习</title>
</head>
<body>
<input type="text" placeholder="请输入第1个数" id="txt1">
<select name="" id="select">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" placeholder="请输入第2个数" id="txt2">
<button id="btn">计算</button>
<input type="text" value="0.00" id="box">
</body>
<script>
// 获取5个页面元素
var txt1 = document.getElementById("txt1");
var txt2 = document.getElementById("txt2");
var select = document.getElementById("select")
var btn = document.getElementById("btn");
var box = document.getElementById("box");
//按钮的点击事件
btn.onclick = function () {
// 获取文本框的value值
var x = Number(txt1.value);
var y = Number(txt2.value);
var op = select.value; // 获取下拉列表的value值
switch (op) {
case "+":
var s = x + y;
break;
case "-":
var s = x - y;
break;
case "*":
var s = x * y;
break;
case "/":
var s = x / y;
break;
default:
console.log("输入有误....");
}
s = s.toFixed(2)
box.value = s;
}
</script>
</html>
效果图: