【问题标题】:Javascript redirect based on date基于日期的 Javascript 重定向
【发布时间】:2012-11-30 17:27:54
【问题描述】:

我希望用户在每月的第一天被引导到 bar.html,在第二个月被引导到 gjb.html,在第三个月被引导到 guerr.html,在其他日期被引导到 error.html。

我做错了什么?无论用户计算机上的日期如何,以下仅加载 bar.html。

<html>
<script type="text/javascript">
    currentTime = new Date();
    if (currentTime.getDate() = 1)
        window.location = "bar.html";
    else if (currentTime.getDate() = 2))
        window.location = "gjb.html";
    else if (currentTime.getDate() = 3))
        window.location = "guerr.html";
    else window.location = "error.html";
</script>
</html>

我对这一切都是全新的,所以像你对一个白痴一样解释它。

【问题讨论】:

  • 看看你的控制台,它应该会说类似 ReferenceError: Invalid left-hand side in assignment

标签: javascript date redirect


【解决方案1】:

只需要进行适当的相等检查,而不是您正在使用的赋值运算符:

<html>
<script type="text/javascript">
    var currentDate = new Date().getDate();
    if (currentDate === 1)
        window.location = "bar.html";
    else if (currentDate === 2))
        window.location = "gjb.html";
    else if (currentDate === 3))
        window.location = "guerr.html";
    else window.location = "error.html";
</script>
</html>

我建议=== 而不是==,因为这样可以进行正确的类型检查,并且可以保证您获得整数,因此这是一种更安全的检查。如有疑问,===

【讨论】:

    【解决方案2】:

    您正在使用currentTime.getDate() = 1 设置日期。试试currentTime.getDate() == 1currentTime.getDate() === 1。 (我不是一直使用 js,但是 '=' 是错误的)。

    【讨论】:

      【解决方案3】:

      尝试使用双等号 (==)。单等号表示赋值,双等号表示比较。

      例子:

      // 为 a 赋值 int a = 1;

      //给b赋值 int b = 2;

      //看a是否等于b

      if( a == b ) {
              System.out.println("They're equal!");
      }
      else {
               System.out.println("They're not equal!");
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-22
        • 2010-11-09
        • 2013-11-26
        • 1970-01-01
        • 2013-10-23
        • 2014-02-28
        相关资源
        最近更新 更多