Javascript 如果值为空

Javascript 如果值为空,javascript,html,Javascript,Html,我有一些代码将用户输入保存到本地存储中,然后将值打印到所选ID中 function saveData() { var input = document.getElementById("saveServer"); localStorage.setItem("server", input.value); console.log(localStorage.getItem("server")); document.getElementById("yourname").innerHTML ="Oka

我有一些代码将用户输入保存到本地存储中,然后将值打印到所选ID中

function saveData() { 
var input = document.getElementById("saveServer");
localStorage.setItem("server", input.value);  
console.log(localStorage.getItem("server"));
document.getElementById("yourname").innerHTML ="Okay  " + (localStorage.getItem("server")) + "  Let's get started! Push the button on the right to begin the story!"  ;   
}
如果输入字段为空,则会生成一条语句,通知用户输入其名称

我已经看过if和else语句,但是我尝试的任何东西似乎都不起作用

编辑:

明白了

if (saveServer.value == "")  {
document.getElementById("yourname").innerHTML = "Please input your name";
} 

else {   
document.getElementById("yourname").innerHTML ="Okay  " + (localStorage.getItem("server")) + "  Let's get started! Push the button on the right to begin the story!"  ;   
}

添加一个条件以检查输入是否为空

function saveData() { 
var input = document.getElementById("saveServer").value;
if(input ==="") alert("Enter saveServer");
else{
  localStorage.setItem("server", input.value);  
  console.log(localStorage.getItem("server"));
  document.getElementById("yourname").innerHTML ="Okay  " + (localStorage.getItem("server")) + "  Let's get started! Push the button on the right to begin the story!"  ;   
  }
}
像这样:

function saveData() {
    var input = document.getElementById("saveServer");
    localStorage.setItem("server", input.value);
    var serverValue = localStorage.getItem("server");
    if (!serverValue) {
        document.getElementById("error").innerHTML = "Oh dear! Nothing was found";
    }
    document.getElementById("yourname").innerHTML = "Okay  " +     (localStorage.getItem("server")) + "  Let's get started! Push the button on the right to begin the story!";
}

Fiddle:

请发布您尝试过的内容。这就像input.value{/*store value*/}else{/*show info*/}一样简单,您可能已经尝试过了,而且应该可以工作。如果不适合你,你必须提供更多信息。谢谢你的快速回答!我自己设法弄明白了,效果很好。你的方式比我的好吗?还是没关系?