基于日期的Javascript重定向

3

我希望用户在每月的第一天被导向到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"(参考错误:赋值语句左侧无效)的内容。 - Elias Van Ootegem
3个回答

3

仅需要使用适当的等于符号进行比较,而不是您正在使用的赋值运算符:

<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>

我建议使用===而不是==,因为它可以进行正确的类型检查,保证您获得整数,这是一种更安全的检查方式。如果不确定,请使用===


1

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

例如:

// 为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!");
} 

1
你正在使用 currentTime.getDate() = 1 来设置日期。请尝试使用 currentTime.getDate() == 1 或者 currentTime.getDate() === 1。(我不是一直在使用js,但是'='是错误的写法)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接