版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengxu_kuangrexintu/article/details/85647320
条件判断
通常写代码的时候,我们需要根据不同的条件执行不同的代码块。那么if语句是一个不错的选择。
if语句
只有当指定条件为 true 时,该语句才会执行代码。
语法一
if (条件){
当条件为 true 时执行的代码
}
举个例子:
if(num >= 60){
alert("及格")
}
语法二
请使用 if…else 语句在条件为 true 时执行代码,在条件为 false 时执行其他代码。
if (条件){
当条件为 true 时执行的代码
}
else
{
当条件不为 true 时执行的代码
}
举个例子
// 判断学生分数 是否及格
var num = 90
if(num >= 60){
alert("及格")
}else{
alert("不及格")
}
if…else if…else 语句
使用 if…else if…else 语句来选择多个代码块之一来执行。
if (条件1){
当条件 1 为 true 时执行的代码
}else if (条件2){
当条件 2 为 true 时执行的代码
}else{
当条件 1 和 条件 2 都不为 true 时执行的代码
}
举例例子:
// 判断学生分数 是否及格
var num = 90
if(num >= 80){
alert("良好")
}else if(num >= 60){
alert("及格")
}else{
alert("不及格")
}
分数判断Demo
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/bootstrap.css" />
<style type="text/css">
input{
width: 100px;
margin-top: 100px;
}
</style>
</head>
<body>
<input id="ipt" type="text" class="form-control" />
<button id="btn" class="btn btn-danger">判断</button>
<script type="text/javascript">
// 需求:判断分数等级
var oIpt = document.getElementById("ipt")
var oBtn = document.getElementById("btn")
oBtn.onclick = function(){
// 60-69 及格
// 70-79 中等
// 80-89 良好
// 90-100 优秀
var num = oIpt.value
if(num >= 90){
alert("优秀")
}else if(num >= 80){
alert("良好")
}else if(num >= 70){
alert("中等")
}else if(num >= 60){
alert("及格")
}else{
alert("不及格")
}
}
</script>
</body>
</html>