开发者

Javascript if statements not working properly on html page

I wrote a script a couple of days ago that would switch the css stylesheet for my page depending upon the time of day. It seemed to work fine until I realized that after it went through the script once, it would just stop.

For Example. When I first implemented the script, it would use one style sheet duing the day, then a different in the evening, then a 3rd one during sunset, and finally once at night. It would do this the first time around. But then after the 4th switch it won't switch again unless I re-implement the script. It just stays on the stylesheet that was switch to at the bottom of the script Since I'm new to javascript I have no开发者_如何学编程 clue why it's doing this.

I have used this same javascript function to control pictures and other things and they seem to work flawlessly. Here is the code.

<!--CSS Stylesheet Switch Code--->

<script type="text/JavaScript">
<!--
function getStylesheet() {
      var currentTime = new Date().getHours();
      if (7 <= currentTime && currentTime < 17) {
       document.write("<link rel='stylesheet' href='http://itsnotch.com/tumblr/files/vice.css' type='text/css'>");
      }
      if (17 <= currentTime && currentTime < 19) {
       document.write("<link rel='stylesheet' href='http://itsnotch.com/tumblr/files/evening.css' type='text/css'>");
      }
      if (19 <= currentTime && currentTime < 21) {
       document.write("<link rel='stylesheet' href='http://itsnotch.com/tumblr/files/dusk.css' type='text/css'>");
      }
      else  {
       document.write("<link rel='stylesheet' href='http://itsnotch.com/tumblr/files/nighttime.css' type='text/css'>");
      }
}

getStylesheet();
-->
</script>


Even if one of the first two statements are correct, one of the last two will always execute. Change your ifs to else ifs, or use a switch.


You should use Javascript If..Else If..If Statement like below:-

if (7 <= currentTime&&currentTime < 17) {
   document.write("<link rel='stylesheet' href='http://itsnotch.com/tumblr/files/vice.css' type='text/css'>");
  }
  else if (17 <= currentTime&&currentTime < 19) {
   document.write("<link rel='stylesheet' href='http://itsnotch.com/tumblr/files/evening.css' type='text/css'>");
  }
  else if (19 <= currentTime&&currentTime < 21) {
   document.write("<link rel='stylesheet' href='http://itsnotch.com/tumblr/files/dusk.css' type='text/css'>");
  }
  else  {
   document.write("<link rel='stylesheet' href='http://itsnotch.com/tumblr/files/nighttime.css' type='text/css'>");
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜