Javascript:根据时间收到问候消息

时间:2017-10-15 19:34:14

标签: javascript

我正在尝试根据时间显示问候语。

为此我创建了日期对象并获取小时并显示每条消息,但由于某些错误,我没有按时间收到问候消息。有谁可以帮助我?

代码:

<!DOCTYPE html>
<html>
<head>
    <title>trail6</title>
</head>
<body>

    <p id="demo"></p>

    <script>

    var today = new Date()
    var curHr = today.getHours()

    if (curHr >= 0 && curHr < 6) {
        document.getElementById("demo").innerHTML = 'What are you doing that early?';
    } else if (curHr >= 6 && curHr <= 12) {
        document.getElementById("demo").innerHTML = 'Good Morning';
    } else if (curHr >= 12 && curHr < 17) {
        document.getElementById("demo").innerHTML = 'Good Afternoon';
    } else {
        document.getElementById("demo").innerHTML = 'Good Evening';
    }

</script>

</body>
</html> 

3 个答案:

答案 0 :(得分:2)

所以你需要将你的一天分成 4套,每套6小时,从0开始......

让数学......

浮动 hour / 24 * 4的结果并将其用作消息索引

&#13;
&#13;
var greet = [
  'What are you doing that early?',
  'Good Morning',
  'Good Afternoon',
  'Good Evening'
][ parseInt(new Date().getHours() / 24 * 4) ];


document.getElementById("demo").innerHTML = greet;
&#13;
<div id=demo></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

<!DOCTYPE html>
<html>
<head>
    <title>trail6</title>
</head>
<body>

    <p id="demo"></p>

    <script>

    var today = new Date()
    var curHr = today.getHours()

    if (curHr >= 0 && curHr < 6) {
        document.getElementById("demo").innerHTML = 'What are you doing that early?';
    } else if (curHr >= 6 && curHr < 12) {
        document.getElementById("demo").innerHTML = 'Good Morning';
    } else if (curHr >= 12 && curHr < 17) {
        document.getElementById("demo").innerHTML = 'Good Afternoon';
    } else {
        document.getElementById("demo").innerHTML = 'Good Evening';
    }

</script>

</body>
</html> 

我在你的前12个之前摆脱了=符号,否则你的代码会正确执行。并向我展示Good Afternoon。我控制台记录它,它工作正常并相应地显示。你必须在中午。因为这是修复之前代码可能破坏的唯一方法。很高兴能回答你的问题。

答案 2 :(得分:-1)

对我来说很好......

<!DOCTYPE html>
<html>
<head>
    <title>trail6</title>
</head>
<body>

    <p id="demo"></p>

    <script>

    var today = new Date()
    var curHr = today.getHours()

    if (curHr >= 0 && curHr < 6) {
        document.getElementById("demo").innerHTML = 'What are you doing that early?';
    } else if (curHr >= 6 && curHr <= 12) {
        document.getElementById("demo").innerHTML = 'Good Morning';
    } else if (curHr >= 12 && curHr < 17) {
        document.getElementById("demo").innerHTML = 'Good Afternoon';
    } else {
        document.getElementById("demo").innerHTML = 'Good Evening';
    }

</script>

</body>
</html>