【问题标题】:How can I run different scripts based on time? [closed]如何根据时间运行不同的脚本? [关闭]
【发布时间】:2016-09-14 07:37:45
【问题描述】:

我是 java-scripts 和 HTML 的基础,所以我想问:如何根据时间运行不同的脚本?, 比如:从早上 6 点到晚上 7 点,执行<script>..</script> 否则执行另一个脚本。


希望我的问题很清楚。

【问题讨论】:

  • 通过检查当前日期时间并执行脚本?到目前为止,您尝试过什么?
  • 我很简单,请用正确的代码回答我:)
  • 你需要展示你已经尝试过的东西。请参阅How to Ask a Good Questionminimal reproducible example
  • Ziad,当然你在javascript方面还很年轻,一步一步爬楼梯,如果你知道这个问题根本不是什么大问题,人们不会在SO上编写免费代码。所以只是,尝试一些你遇到的问题回来,人们会提供帮助

标签: javascript time


【解决方案1】:

var hour = new Date().getHours(); // hour will get current hour like 0 to 23 switch(hour) { case '6': // code in this case will run if current time is in 6am to 7am alert('hi, it's in 6 a.m to 7 a.m now'); break; case '7': // any other hour // add your code you want to run between 7 - 8 am break; }

【讨论】:

  • 非常非常感谢:)
  • 如果您想要像“凌晨 2 点 - 早上 6 点”这样的跨小时时段,您可以将 case '2' 叠加到 case '5'。但在这种情况下,if(){} else {} 效果更好。
  • 顺便说一下,使用更方便的“IDE”。我喜欢 atomVisualStudio Code,免费且跨平台。
【解决方案2】:

您可以使用new Date().toLocaleString().match()RegExp /\d+(?=\:)/.split()RegExp /.*\s/

var now = new Date().toLocaleString().split(/,/)[1].trim();

var curr = now.match(/\d+(?=\:)/), ampm = now.split(/.*\s/)[1];

if ((curr >= 6 && ampm === "AM") || (curr < 7 && ampm === "PM")) {
  // do stuff
}

【讨论】:

    【解决方案3】:

    如果您希望页面跳转到所需位置,我相信您想使用 location.href 而不是 href。您还必须在处理页面后执行代码,以便已经定义了锚点。这可以通过将脚本放在正文的末尾或使用 window.onload 或 document.onload 设置在加载页面功能后执行的方法来完成。下面这种情况下,跳转是由一个按钮触发的。

    <!DOCTYPE html>
    <html>
    <head>
    <title>Using hour of day in Javascript</title>
    <script>
    function processDate() {
       var outField = document.getElementById("out");
       var date = new Date();
       var time = date.getHours();
       alert("Hour is " + time);
       outField.value = time;
       location.href="#5";
    }
    </script>
    </head>
    <body>
    <p>See:</p>
    <ul>
    <li><a href="http://www.w3schools.com/js/js_dates.asp"
        target="_blank">http://www.w3schools.com/js/js_dates.asp</a></li>
    <li><a href="http://www.w3schools.com/jsref/jsref_obj_date.asp"
        target="_blank">
        http://www.w3schools.com/jsref/jsref_obj_date.asp</a></li>
    </ul>
    <form>
    <p><input type="button" onclick="processDate()" value="Show Date"></input></p>
    <p><input type="text" id="out" size="50"></input></p>
    </form>
    <p><a name="5">This is point 5</a></p>
    </body>
    </html>
    

    【讨论】:

    • 非常感谢,很有帮助
    猜你喜欢
    • 2013-09-27
    • 1970-01-01
    • 2020-10-17
    • 2014-11-13
    • 2017-08-27
    • 1970-01-01
    • 2013-05-17
    • 2019-09-10
    • 2019-12-23
    相关资源
    最近更新 更多