在每次打开HomePage时显示加载和存储值以提示用户

时间:2018-01-20 18:01:00

标签: javascript html prompt sessionstorage

我正在尝试向用户询问“你的名字是什么”,使用提示信息获取其名称。然后,根据当前时间向用户发出欢迎消息。 到目前为止,我只能通过点击按钮来显示消息。 我想要做的是首先询问名称,一旦获得用户名,在加载HomePage时直接显示消息。

这是HTML:

 <form> 
    <input id="show_button" class="button" type="button"   value="Hey! Click Me! I know you!" onclick="greet(), salutoTempo()" /> 
</form>

这是JavaScript代码:

var today = new Date();
var hourNow = today.getHours();   
var saluto;

   
if (hourNow > 17) {   
  saluto = "Good evening"
} else if (hourNow > 11) {
  saluto = "Good afternoon"
} else if (hourNow > 0) {
  saluto = "Good morning"
} else {
  saluto = "Welcome to Wolf the Barber!"
}

var el = document.getElementById("greeting");





function salutoTempo(){
			document.getElementById("greeting").innerHTML = saluto + " ";
}




function greet(){
   name = localStorage.getItem("name");
   if (name == null || name == "null"){
     alert("Hi, Stranger!");
     name = prompt("What is your name?");
     localStorage.setItem("name", name);
     var greeting = document.getElementById("greeting").innerHTML = (greeting);
     var Username = document.getElementById("greeting1").innerHTML = (name + "!");
 } else {
     var greeting = document.getElementById("greeting").innerHTML = (greeting);
     var Username = document.getElementById("greeting1").innerHTML = (name + "!");
   } // end greet
 } // end function

谢谢你们!

1 个答案:

答案 0 :(得分:0)

根据您的问题,您可以在onload标记中使用body属性。另外,调用函数salutoTempo

<html>
<body onLoad = "greet()">
 <form> 
    <input id="show_button" class="button" type="button"   value="Hey! Click Me! I know you!" onclick="greet(), salutoTempo()" /> 
</form>

<span id="greeting"></span>
<br>
<span id="greeting1"></span>

<script>
var today = new Date();
var hourNow = today.getHours();   
var saluto;

if (hourNow > 17) {   
  saluto = "Good evening"
} else if (hourNow > 11) {
  saluto = "Good afternoon"
} else if (hourNow > 0) {
  saluto = "Good morning"
} else {
  saluto = "Welcome to Wolf the Barber!"
}

var el = document.getElementById("greeting");

function salutoTempo(){
    document.getElementById("greeting").innerHTML = saluto + " ";
}


function greet(){
   name = localStorage.getItem("name");

   if (name === null || name === "null"){
     alert("Hi, Stranger!");
     name = prompt("What is your name?");
     localStorage.setItem("name", name);     
     document.getElementById("greeting1").innerHTML = (name + "!");
   } else {
     document.getElementById("greeting1").innerHTML = (name + "!");
   } // end greet
   salutoTempo();
} // end function
</script>
</body>
</html>