javascript - else if 语句在第一次迭代之后不会触发

标签 javascript html if-statement

我正在尝试使用 if 和 else 语句来根据季节显示图片。
对于 var currentMonth = new Date().getMonth(); ,它返回当前月份为 0-11 0 是一月,11 是十二月。现在我相当确定我的问题在于我的方式执行 else if 语句。当我更改桌面日期时,无论我使用哪个月份,它都只会显示冬季或 Spring 的图像。它会在应该显示冬季图像的时候显示冬季图像,但在所有其他月份中都会显示 Spring 图像。这对我来说是 else if 语句的问题。任何帮助将不胜感激

<script language="javascript">

  function retrievePictures(){
    var currentMonth = new Date().getMonth();


    if(currentMonth >= 10 || currentMonth <=1){
      //winter
      var html = '<img src="img/hall-of-gods.jpg" width="600" height="400" alt="Hall Of The Gods" />';

    }

    else if(currentMonth >= 2 || currentMonth <=4){
      //spring
      var html = '<img src="img/merlyn.jpg" width="600" height="400" alt="Spring Time Cat" />';

    }

    else if(currentMonth >= 5 || currentMonth <=7){
      //summer    
      var html = '<img src="img/bounty.jpg" alt="Summer Bounty" width="600" height="400" />';

    }

    else{
      //autum    
      var html = '<img src="img/louis.jpg" alt="King Louis" width="600" height="400" />';

    }
    document.write(html);
  }
</script>



<div class="slideshow">
  <script type="text/javascript">
    retrievePictures();
  </script>
</div>

最佳答案

尝试使用switch case而不是大量的if else。 语法更加清晰易懂。另外,您可以在 switch 语句之前仅声明一次,而不是在变量 html 上声明 4 次。

var currentMonth = new Date().getMonth();
var html ='';
switch (currentMonth) {
    case 10:
    case 11:
    case 0:
        //winter
      html = '<img src="img/hall-of-gods.jpg" width="600" height="400" alt="Hall Of The Gods" />';
   break;

    case 2:
    case 3:
    case 4:
    //spring
        html = '<img src="img/merlyn.jpg" width="600" height="400" alt="Spring Time Cat" />';
        break;
    case 5:
    case 6:
    case 7:
//summer 
        html = '<img src="img/bounty.jpg" alt="Summer Bounty" width="600" height="400" />';
        break;
    case 8:
    case 9:
      //autum 
         html = '<img src="img/louis.jpg" alt="King Louis" width="600" height="400" />';
        break;
}

关于javascript - else if 语句在第一次迭代之后不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46016322/

相关文章:

javascript - jQuery UI 日期选择器 : onSelect called twice

javascript - ajax-如何阻止浏览器显示ajax url

javascript - HTML多个ul>li使用jquery来回遍历

python - 如何不通过大写其他代码来替换代码?

javascript - 迭代对象的属性 Knockoutjs

javascript - 自定义刻度、值和格式

javascript - 如何使用 javascript 打开模态并显示内容

javascript - 套接字 IO 不发送数组

jquery - if 语句运行失败

swift - if 语句返回的值不适用于 UiLabel