我正在尝试使用 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/