2016-09-28 37 views
-2

我有一个index.html,在此文件中,我编写代码以便在此显示一条消息“hello”。我的目标是实现显示三种消息的代码:“早上好”,“晚上好”和“晚安”。如何通过Javascript中的if语句显示消息

跟随我的代码:

<p id="show_time" class="time"></p> 
<script> 
window.onload = show_time('show_time'); 

    function show_time(id) { 
     h = date.getHours(); 

     if h == 22 { 
     document.getElementById(id).innerHTML = "hello"; 
     } 
     setTimeout('show_time("' + id + '");','1000'); 
     return true; 
    } 
} 

在这段代码中我只写了一个情况。类,时间是包含字体大小和字体系列的css属性。 h获取当前小时,如果h为22,则将输出“hello”。但这不起作用。

如果您可以提供显示三种消息类型的代码,它非常有用。

谢谢

+0

'H> 0 &&ħ<= 16'节目( “早上好”)。 “h> 16 && h <= 20”表演(“晚上好”)。 'h> 20 && h <= 24'表演(“晚安”)。像这样? –

+0

写在如果不合格。 'if(h == 22){// your code}' –

+0

if(h == 22){will工作 –

回答

2

window.onload = function() { 
 
    var h = new Date().getHours(), 
 
     msg = 'morning'; 
 
    
 
    if (h > 12) { msg = 'afternoon'; } 
 
    if (h > 20) { msg = 'night'; } 
 

 
    document.getElementById('show_time').innerHTML = msg; 
 
}
<p id="show_time" class="time"></p>

+0

我想知道是否可以通过括号内的样式更改msg颜色。喜欢这个; {msg ='afternood'; msg.style.color ='orange'; }这段代码不起作用,所以如果你知道它的帮助。谢谢 – bagels

+0

你必须改变'#show_time'元素的样式,而不是msg –

+0

啊我看到了!我感谢他 – bagels

0

像这样?? ??

/* next line if false, see the comments on this answer!!! */ 
 
window.onload = show_time('show_time'); 
 

 
function show_time(id) { 
 
    var date = new Date(), 
 
     h = date.getHours(); 
 

 
    if(h > 0 && h < 6) { 
 
    var msg = "Good night"; 
 
    } 
 
    else if(h >= 6 && h < 12) { 
 
    var msg = "Good morning"; 
 
    } 
 
    else if(h >= 12 && h < 18) { 
 
    var msg = "Good day"; 
 
    } 
 
    else if(h >= 18 && h < 24) { 
 
    var msg = "Good evening"; 
 
    } 
 
    document.getElementById(id).innerHTML = msg; 
 
    setTimeout('show_time("' + id + '");', '1000'); 
 
}
<p id="show_time" class="time"></p>

+1

'window.onload = show_time('show_time');'看起来不好,'window.onload'需要一个函数的引用。 – Titus

+0

@Titus,查看第二个例子:https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload – LinkinTED

+1

我已经检查过了。它不是load()',而是'load',是对函数的引用,而不是运行该函数的结果。它应该是'window.onload = show_time'或'window.onload = show_time.bind(this,'show_time');'以传递参数。 – Titus