10-JavaScript 条件语句

时间:2020-07-15 15:35:19   收藏:0   阅读:61

1、条件语句分类

2、if 语句

  只有当指定条件为 true 时,该语句才会执行代码。

  语法:

  if (condition)
  {
      当条件为 true 时执行的代码
  }

  实例:

  <p>如果时间早于 20:00,会获得问候 "Good day"。</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";
  }
    document.getElementById("demo").innerHTML=x;
  }
  </script>

  注意:

  在这个语法中,没有 ..else..。您已经告诉浏览器只有在指定条件为 true 时才执行代码。

3、if...else 语句

  请使用 if....else 语句在条件为 true 时执行代码,在条件为 false 时执行其他代码。

  语句:

  if (condition)
  {
      当条件为 true 时执行的代码
  }else{
      当条件不为 true 时执行的代码
  }

  实例:

  <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>

4、if...else if...else 语句

  使用 if....else if...else 语句来选择多个代码块之一来执行。

  语法:

  if (condition1){
      当条件 1 为 true 时执行的代码
  }else if (condition2){
      当条件 2 为 true 时执行的代码
  }else{
    当条件 1 和 条件 2 都不为 true 时执行的代码
  }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!