简体   繁体   English

使用Javascript根据时间更改文本

[英]Change Text based on time with Javascript

Right now I'm pulling in the current time in the span #time , and would like to add custom messages into #officehours based on the time, but am having trouble getting them to play nicely with each other.现在,我在跨度#time中提取当前时间,并希望根据时间将自定义消息添加到#officehours中,但无法让它们相互配合。

 //Timestamp function getTimeCurrentTime() { let time = new Date(); return time.toLocaleString('en-US').split(',')[1]; } function updateCurrentTime() { let timeNode = document.getElementById('time'); timeNode.innerHTML = getTimeCurrentTime(); } setInterval(updateCurrentTime, 1000); function officeHours() { var myDate = new Date(); var hrs = myDate.getHours(); var greet; if (hrs < 12) greet = 'Good Morning'; else if (hrs >= 12 && hrs <= 17) greet = 'Good Afternoon'; else if (hrs >= 17 && hrs <= 24) greet = 'Good Evening'; document.getElementById('officehours').innerHTML = greet; }
 <div class="timecontainer"> <span>Office Hours:</span><br> <span>MF, 9:00-5:00</span><br> <span>Currently:</span><span id="time"></span><br> <span>We Are:</span><span id="officehours"></span> </div>

Call the function.调用函数。

You've defined a function called updateCurrentTime :您已经定义了一个名为updateCurrentTime的函数:

function updateCurrentTime() {
  //...
}

And you call it at 1-second intervals:你每隔 1 秒调用一次:

setInterval(updateCurrentTime, 1000);

You've also defined a function called officeHours :您还定义了一个名为officeHours的函数:

function officeHours() {
  //...
}

But you never call it.但你永远不会调用它。 In order to execute a function, you have to invoke it.为了执行一个函数,你必须调用它。 Presumably in this case the intent is to invoke it from the updateCurrentTime function.大概在这种情况下,意图是从updateCurrentTime函数调用它。 For example:例如:

function updateCurrentTime() {
  let timeNode = document.getElementById('time');
  timeNode.innerHTML = getTimeCurrentTime();
  officeHours();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM