JavaScript 中的条件语句
JavaScript 中有三种类型的条件语句 -
- If 语句 - if 语句用于仅在满足特定条件时执行 if 块内的代码。
- If else 语句 - If...Else 语句用于仅检查两个条件,并为每个条件执行不同的代码。
- If else if else 语句 - If...else if...else 语句常用于检查两个以上的条件。
以下是 JavaScript 中实现条件语句的代码 -
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body>
<h1>Conditional statements in JavaScript</h1>
<input type="text" class="numInput" />
<button class="Btn">CHECK</button><br />
<div class="result"></div>
<h3>Click on the above button to see if the above number is divisible by 2,3 or both</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
let numInputEle = document.querySelector(".numInput");
BtnEle.addEventListener("click", () => {
if (numInputEle.value % 2 === 0 && numInputEle.value % 3 === 0) {
resEle.innerHTML = "The numbers is divisible by 2 and 3 both";
} else if (numInputEle.value % 3 === 0) {
resEle.innerHTML = "The number is divisbly by 3";
} else if (numInputEle.value % 2 === 0) {
resEle.innerHTML = "The numbers is divisible by 2";
} else {
resEle.innerHTML = "The numbers isn't divisible by 2 or 3";
}
});
</script>
</body>
</html>输出

在输入一个数字并点击“检查”按钮时 -

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP