当前阅读教程:JavaScript教程 > if...else 语句 | |
阅读(22555525) 收藏 赞(5685) 分享 | |
上一篇: if 语句 | 下一篇: if...else if...else 语句 |
请使用 if....else 语句在条件为 true 时执行代码,在条件为 false 时执行其他代码。 语法 if (condition) { 当条件为 true 时执行的代码 } else { 当条件不为 true 时执行的代码 } 实例 当时间小于 20:00 时,生成问候 "Good day",否则生成问候 "Good evening"。 if (time<20) { x="Good day"; } else { x="Good evening"; } x 的结果是: Good day 完整代码 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>小白教程网 2d5.net</title> </head> <body> <p>点击这个按钮,获得基于时间的问候。</p> <button onclick="myFunction()">点击这里</button> <p id="demo"></p> <script> function myFunction(){ var x=""; var time=new Date().getHours(); if (time<20){ x="Good day"; } else{ x="Good evening"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html> 效果图 |
|
上一篇: if 语句 | 下一篇: if...else if...else 语句 |