知识点:if、if…else、if…else if…else
if: 只有当指定条件为 true 时,使用该语句来执行代码
var x=5;
if(x=5){
//花括号里面是if()为true时执行的代码,为false就不会执行代码
alert(“hello World”);
}
输入结果:hello World
if…else:当条件为true时执行if的代码,否则执行else的代码
var x=6;
if(x<5){
//花括号里面是if()为true时执行的代码
alert("hello World");
}else{
//花括号里面是if()为false时执行的代码
alert("Hello World");
}
输出结果为:Hello World
if…else if…else: 使用该语句来选择多个代码块之一来执行其他代码
语法:
if(条件1){
当条件1为true时执行的代码
}else if(条件2){
当条件2为true时执行的代码
}else{
当条件1和条件2都不为true时执行的代码
}
HTML代码
<p>点击这个按钮,获得基于时间的问候。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
如果时间小于10:00,则将发送问候“Good morning”,否则如果时间小于20:00,则发送问候“Good day”,否则 发送问候“Good evening”
function myFunction(){
var x="";
var time=new Date().getHours();//getHours返回Date对象的小时 (0 ~ 23)
if(time<10){
x="Good morning";
}else if(time<20){
x="Good day";
}else{
x="Good evening";
}
}