如何根据时间运行不同的脚本
How can I run different scripts based on time?
我是java脚本和HTML的基础,所以我想问:如何根据时间运行不同的脚本?,比如:从早上6点到晚上7点,做<script>..</script>
,否则做另一个脚本。
希望我的问题很清楚。
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;
}
您可以将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
}
如果您希望页面跳转到所需位置,我相信您希望使用location.href而不是href。您还必须在页面处理后执行代码,以便已经定义了锚点。这可以通过将脚本放在正文的末尾来完成,也可以使用window.onload或document.onlead来设置在加载页面功能后执行的方法。在以下情况下,跳跃由按钮触发。
<!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>
- Google 脚本:用于创建日历活动的脚本运行时不会出错,但不会执行任何操作
- Chrome没有加载最新版本的web工作程序脚本(运行缓存版本)
- 从 jquery.ready() 调用的 javascript 何时相对于 中的脚本运行
- 如何从其中的另一个jquery脚本运行.load()
- 这个对象构造函数阻止我的脚本运行
- 当作为脚本运行时.js Node中“this”的上下文是什么
- 如何使 Tampermonkey 添加的函数在脚本运行后在控制台中可用
- 当脚本运行时,它每秒将 4px 添加到我的容器的高度,只发生在 Firefox 中
- 我可以阻止我的 HTML 页面加载,直到我的 Facebook 登录状态脚本运行之后
- 从 PHP 脚本运行 Javascript 函数
- 我如何将脚本运行到从 jQuery 加载特定标签加载的另一个页面
- 在 PHP 脚本运行时添加加载图像
- 在IE中导致“脚本运行缓慢”警告
- Javascript - 脚本 1 停止,直到脚本 2 运行
- 脚本运行不正确的功能
- ajax脚本运行后指向页面的链接(javascript锚点?)
- 在脚本运行之前终止与浏览器的连接
- 脚本运行时,无法从FTP服务器自动下载文件
- 如何在外部JS脚本运行完成后运行函数
- 根据设备大小阻止脚本运行