简体   繁体   English

为什么我的Javascript代码无法正常工作?

[英]Why is my Javascript code not working correctly?

I recently started working with Javascript, like a few hours ago, and I can't figure out why it's still showing text it shouldn't be on my website. 我最近才开始使用Javascript,就像几个小时前一样,我不知道为什么它仍在显示文本,而不应该在我的网站上显示。 Dreamweaver says no error, but there has to be.. Dreamweaver说没有错误,但是必须有..

<script type="text/javascript">
     var day = new Date();
     var hr = day.getHours();
     if((hr == 1) || (hr == 2) || (hr == 3) || (hr == 4) || (hr == 5) || (hr == 6) || (hr == 7) || (hr == 8) || (hr == 9)); {
         document.write("Paragraph one stack example");
     }
    if(hr == 10) {
        document.write("P2 stack ex");
    }
    if((hr == 11) || (hr == 12) || (hr == 13)); {
        document.write("P3 stack ex.");
    }

</script>

From your code, slightly reformatted: 从您的代码中,稍微重新格式化:

if((hr == 1) || ... || (hr == 9)); {
    document.write("Paragraph one stack example");
}

Get rid of that semicolon, it's making the entire if bit irrelevant. 摆脱分号,它使得整个if有点文不对题。

What it translates to is: 它的意思是:

if((hr == 1) || ... || (hr == 9))
    ;
{
    document.write("Paragraph one stack example");
}

In other words, 换一种说法,

  • if hr is 1-9, do nothing. 如果hr是1-9,则什么也不做。
  • regardless of the value of hr , output "Paragraph one stack example". 无论hr的值如何,都输出“段一堆栈示例”。

You have the same problem with the if statement for 11/12/13 as well. 你必须用同样的问题if for语句11/12/13为好。


A better solution for that "one through nine" if statement, by the way, would be: 顺便说一下,对于“ 1到9” if语句, 更好的解决方案是:

if((hr >= 1) && (hr <= 9)) {
    document.write("Paragraph one stack example");
}

and you can further clean up the code since all the conditions are mutually exclusive: 由于所有条件都是互斥的,因此您可以进一步清理代码:

<script type="text/javascript">
    var day = new Date();
    var hr = day.getHours();
    if ((hr >= 1) || (hr <= 9)) {
        document.write("Paragraph one stack example");
    } else if (hr == 10) {
        document.write("P2 stack ex");
    } else if ((hr >= 11) && (hr <= 13)) {
        document.write("P3 stack ex.");
    }
</script>

There's little point checking if hr is equal to 10 if you've already established that it's 4 , for example. 例如,如果您已经确定hr等于4 ,那么几乎没有必要检查hr是否等于10 So you can use else if for that. 因此,您可以使用else if

Code is valid, but you have done mistake when put 代码有效,但放置时您犯了错误

; ;

at the end of if expression 在if表达式的末尾

if you remove this all will works fine! 如果将其删除,则一切正常!

 var day = new Date(); var hr = day.getHours(); if((hr == 1) || (hr == 2) || (hr == 3) || (hr == 4) || (hr == 5) || (hr == 6) || (hr == 7) || (hr == 8) || (hr == 9)) { document.write("Paragraph one stack example"); } if(hr == 10) { document.write("P2 stack ex"); } if((hr == 11) || (hr == 12) || (hr == 13)) { document.write("P3 stack ex."); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM