【问题标题】:how to check for localStorage value, before page loads如何在页面加载之前检查 localStorage 值
【发布时间】:2018-04-28 11:30:07
【问题描述】:

我在index.html 中有一个名为validateLogin 的函数,我在其中设置了本地存储值键userID,在返回此函数的true 时,我加载了其他网页(home.html),其中我使用了这个 local-Storage 值 userID,但是现在,如果在没有 validateLogin 函数的情况下直接访问 home.html 时 local-Storage 为空或 localStorage 为空,我需要限制用户并将它们重定向到 signup.html , 我在下面尝试了但它不起作用,我做错了什么?

index.html

<form id="login_form" name="login" action="home.html" method=POST onsubmit="return validateLogin()">
<script>
  var userid;
  function validateLogin() {
    userid = document.getElementById('user_id').value;
    localStorage.setItem("userID",userid);
    var passid = document.getElementById('pass_id').value;
    if ((userid.length < 3) || (passid.length < 6)) {
      document.getElementById('user_error').setAttribute("style", "color:red")
      document.getElementById('user_error').innerHTML = "invalid username/password.";
      return false;
    }
    preventBack();
    return true;
  }
</script>

home.html

<body>
  <!--Navigation bar-->
  <div id="nav-placeholder">
  </div>
  <!--end of Navigation bar-->

<script>
  window.onload = checkUser;
  function checkUser(){
    if(localStorage.getItem("userID") === "") {
      window.location ="signup.html";
    } 
    else {
      $("#nav-placeholder").load("nav_auth.html");
    }
  };
  </script>
</body>

【问题讨论】:

  • 删除window.onload = checkUser; function checkUser(){和最后一个};
  • 试过了,还是不行
  • 那么你想在加载 home.html 后立即检查 localStorage 数据是否存在吗?或者你想在加载完成时检查它?
  • if (localStorage.getItem("userID")) ("#nav-placeholder").load("nav_auth.html"); else window.location.replace("signup.html");
  • 感谢@mplungjan ..它现在可以工作,但不知道为什么其他部分不工作

标签: javascript html local-storage


【解决方案1】:

localStorage.getItem 如果键不存在,则返回 null,同时您正在对空字符串进行严格的相等性检查。

替换

if (localStorage.getItem("userID") === "")

if (!localStorage.getItem("userID"))

【讨论】:

  • 我重新创建了您的 home.html 并将 if (localStorage.getItem("userID") === "") 更改为 if (!localStorage.getItem("userID"))。它按预期重定向到 signup.html。确保您在 localStorage 中还没有用户 ID。
【解决方案2】:
localStorage.getItem("toto")

如果没有找到键返回null,所以你应该检查null而不是空字符串

【讨论】:

    【解决方案3】:
    if(!localStorage.getItem("userID")){
    
    }
    

    为我工作

    【讨论】:

      【解决方案4】:

      如果脚本标签在页面底部,则不需要 window.onload = checkUser;所以删除它。 在函数的开头放置一个加载器,检查用户 ID 是否存在,如果它没有让用户保持登录/注册状态,则导航到主页。

      【讨论】:

        【解决方案5】:

        你可以通过它检查它。

        if ("userId" in localStorage) {
                        alert('yes');
                        
                    } else {
                        alert('no');
                    }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-05-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-18
          • 1970-01-01
          • 2010-12-23
          相关资源
          最近更新 更多