else if语句应用十分广泛,通过该语句做个简单问候语的功能;
首先定义个变量获取当前时间,在应用getHours()方法获取系统当前小时值,在使用else if语句判断时间段输出问候语;
html代码:
<button onclick="date()">点击</button>
JS代码
<script> function date(){ var now=new Date(); var h=now.getHours(); if(h>5&&h<=7){ alert("早上好!"); }else if(h>7&&h<=11){ alert("上午好"); }else if(h>11&&h<=13){ alert("中午好"); }else if(h>13&&h<=17){ alert("下午好"); }else if(h>17&&h<=21){ alert("晚上好"); }else if(h>21&&h<=23){ alert("夜深了,注意身体"); }else{ alert("凌晨了,该休息了"); } } </script>
文章评论