例: 代码如下: <script> function myFunction() { var x=""; var time=new Date().getHours(); if (time<20) { x="Good day"; } document.getElementById("demo").innerHTML=x; } </script>
if...else...语句 if(条件){ 当条件为true时,执行代码 }else{ 当条件不为true时(条件为false),执行的代码; } 例: 代码如下: <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>
if...else if...else...语句 if(条件1){ 当条件1为true时,执行代码; }else if(条件2){ 当条件2为true时,执行代码; }else{ 当条件1和2 都不为true时 ,执行的代码; } 例: 代码如下: <script> function myFunction() { var x=""; var time=new Date().getHours(); if (time<10) { x="Good morning"; } else if (time<20) { x="Good day"; } else { x="Good evening"; } document.getElementById("demo").innerHTML=x; } </script>