首页 > 解决方案 > 检查localStorage中是否有值,如果没有显示替代消息(Javascript)

问题描述

我仍然是新手开发人员,非常感谢一些帮助。当用户在测验中得分 10/10 时,从另一个函数中调用下面的函数 on()。用户名最初是从不同页面上的用户名登录创建的,并且该值成功存储在 localStorage 中。该部分工作正常,如果我省略了第一个“if”语句行和整个“else if”语句,我可以使用以下语句的第一部分调用该值(在 on() 函数中)。但是,我试图在用户不输入用户名的情况下迎合时间,因为当调用 on() 函数的第一部分时,它会显示以下内容:“恭喜{null}!你获得了完美的 10 分”。我希望它在下面的“else if”部分中显示备用消息。

function on() {
    if (localStorage.getItem("users") == true) {
    document.getElementById("overlay").style.display = "block";
    document.getElementById("overlay").innerText = "Congratulations " +
    window.localStorage.getItem('users') + "! You scored the perfect 10!";
    } else 
    if (localStorage.getItem("users") === null) {
    document.getElementById("overlay").style.display = "block";
    document.getElementById("overlay").innerText = "Congratulations! You scored the perfect 10!";
}

标签: javascript

解决方案


推荐阅读