在问候之前显示人

时间:2018-04-05 11:47:13

标签: javascript html

嗨我需要那两个显示在同一行(现在他们一个接一个地显示)。我尝试了很多东西但没有任何作用。

document.write();
var day = new Date();
var hr = day.getHours();

if ((hr == 1) || (hr == 2) || (hr == 3) || (hr == 4) || (hr == 5) || (hr == 
6) || (hr == 7) || (hr == 8) || (hr == 9) || (hr == 10)  || (hr == 11) || 
(hr == 12)) {
document.write("Good Morning!");
} 
if ((hr == 13) || (hr == 14) || (hr == 15) || (hr == 16) || (hr == 17)) {
document.write("Good Afternoon!");
}
if ((hr == 18) || (hr == 19) || (hr == 20) || (hr == 21) || (hr == 22) || 
(hr == 23) || (hr == 24)) {
document.write("Good Evening!");
}

document.write();
/*-------------------------------------------------------------------------- 
---------------------------*/
function myFunction() {
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
    document.getElementById("demo").innerHTML =
    person;
}
}

3 个答案:

答案 0 :(得分:1)

这就是你要找的东西:

<html>
<body onload="myFunction()">
<div id="demo"></div>
<script>
function myFunction() {
    var day = new Date();
    var hr = day.getHours();
    var greeting;
    var person = prompt("Please enter your name", "Harry Potter");
    if (person != null) {
        if ( hr <= 12 ) {
            greeting = "Good morning " + person;
        } else if ( hr <= 18 ) {
            greeting = "Good afternoon " + person;
        } else {
            greeting = "Good evening " + person;
        }
        document.getElementById("demo").innerHTML = greeting;
    }
}
</script>
</body>
</html>

答案 1 :(得分:0)

  

我希望这会帮助你。我也为if做了代码优化   条件。   您必须调用myfunction方法

    <body>
        <span id="demo"></span>
        <script>
        (function () {
        var person = prompt("Please enter your name", "Harry Potter");
        if (person != null) {
        document.write();
        var day = new Date();
        var hr = day.getHours();

        if ((hr >= 1) && (hr <= 12)) {
        person = person + " Good Morning!";
        } 
        else if ((hr >= 13) && (hr <= 17)) {
        person = person + " Good Afternoon!";
        }
        else if ((hr >= 18) && (hr <= 24)) {
        person = person + "Good Evening!" ;
        }
            document.getElementById("demo").innerHTML = person;
        }
        })()

        </script>
 </body>

答案 2 :(得分:0)

document.write()不会向文档添加新行,而是将文档元素更改为内容,其中document.getElementById()引用DOM中的特定元素。无论如何这里是我的 的的javascript:

function greeting() {
  var person = prompt("Please enter your name", "Harry Potter");

  if (person != null) {
    // Set hr to current hour
    var hr = new Date().getHours();

    // Tests current hour
    if (hr > 0 && hr < 13) {
        document.write("Good Morning! " + person);
    } else if (hr > 12 && hr < 18) {
        document.write("Good Afternoon! " + person);
    } else if (hr > 17 && hr < 25) {
        document.write("Good Evening! " + person);
    }
  }
}