我正在尝试根据时间更改此元素:text
我找到了这个片段,但是我更改/添加了什么以便它影响h1?
var list = [{name: "foo", surname: "bar"}, {name: "Jean", surname: "dupond"}];
function msgAfterTimeout(who, timeout) {
return new Promise(resolve =>
setTimeout(
() => resolve(" Hello " + who + "!"),
timeout)
);
}
Promise.all(
list.map(item => msgAfterTimeout(item.name, 200))
).then(
result => console.log(result.join('\n'))
);
提前感谢!
答案 0 :(得分:1)
您的页面上需要有一个h1标记,并且您可以提供' id'属性并根据当前时间更改内容:下面的代码可以帮助您
var myDate = new Date(); /* hour is before noon */ if (
myDate.getHours() < 12 ) {
document.getElementById('greeting').innerHTML ="Good Morning!"; }
else if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{ document.getElementById('greeting').innerHTML ="Good Afternoon!"; }
else if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{ document.getElementById('greeting').innerHTML= "Good Evening!"; }
else
{ document.getElementById('greeting').innerHTML="I'm not sure what time it is!"; }
&#13;
<h1 id="greeting"></h1>
&#13;
答案 1 :(得分:0)
您可以将document.write(...)
更改为document.getElementsByTagName('h1')[0].write(...)
这会写入您网页中的第一个h1
标记
答案 2 :(得分:0)
使用JQuery:
var myDate = new Date();
var text = "";
/* hour is before noon */
if ( myDate.getHours() < 12 ) {
text = "Good Morning!";
}
/* Hour is from noon to 5pm (actually to 5:59 pm) */
else if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 ) {
text = "Good Afternoon!";
}
/* the hour is after 5pm, so it is between 6pm and midnight */
else if ( myDate.getHours() > 17 && myDate.getHours() <= 24 ) {
text = "Good Evening!";
}
/* the hour is not between 0 and 24, so something is wrong */
else {
text = "I'm not sure what time it is!";
}
$("h1").text(text);
如果没有JQuery,最后一行将是:
var h1s = document.getElementsByTagName('h1');
for(var i = 0; i < h1s.length; i ++) {
h1s[i].innerHTML = text;
}