This question already has an answer here: Javascript - turning if statement into switch statement                                                                    (1个答案)                                                                                        2年前关闭。                                它在if / else语句上运行良好,但是一旦使用switch语句,即使本地时间小于24(凌晨12点),也仅显示默认消息。一如既往地感谢您的帮助。 var today = new Date(); var timeNow = today.getHours() var greeting = $("#greeting");switch (timeNow) { case timeNow > 17 : greeting = "Good Evening </br> Welcome To My Website"; break; case timeNow > 12 : greeting = "Good Afternoon </br> Welcome To My Website"; break; case timeNow > 6 : greeting = "Good Morning </br> Welcome To My Website"; break; default: greeting = "Welcome... but isn't it bed time now?"; } $('#greeting').html('<h1>' + greeting + '<h1>');<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h1 id="greeting">Welcome!</h1> 最佳答案 您的switch语句试图将timeNow的值与timeNow > 17的结果进行比较,这样的结果将是布尔值(true或false)。自然,没有一个匹配,因为没有Date实例是===或true。您原来的false可能是正确的选择。但是,您可以在JavaScript中为此使用if/else if/else(与许多其他语言不同),因为switch值可以是表达式,并且它们按照源代码顺序进行评估,并且仅使用第一个匹配的值(除了,如果其他都不匹配则总是最后使用)。所以如果你改变switch (timeNow) {至switch (true) {...然后将case与default的结果进行比较,例如:var today = new Date(); var timeNow = today.getHours() var greeting = $("#greeting");switch (true) { // <=== Change is here case timeNow > 17 : greeting = "Good Evening </br> Welcome To My Website"; break; case timeNow > 12 : greeting = "Good Afternoon </br> Welcome To My Website"; break; case timeNow > 6 : greeting = "Good Morning </br> Welcome To My Website"; break; default: greeting = "Welcome... but isn't it bed time now?"; } $('#greeting').html('<h1>' + greeting + '<h1>');<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h1 id="greeting">Welcome!</h1>再次提醒您:原始的true可能是正确的选择。关于javascript - 使用switch语句在javascript中更改小时后显示不同的消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41676229/
10-13 05:44