我在validateLogin
中有一个名为index.html
的函数,我设置了本地存储值键userID
,并在此函数的返回true
上加载其他网页-page(home.html)我使用了这个本地存储值userID
,但是现在,我需要限制用户并将它们重定向到signup.html,如果home.html
是local-Storage为空直接访问没有validateLogin
函数或localStorage为空,
我在下面试过但是它不起作用,我做错了什么?
的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>
答案 0 :(得分:0)
localStorage.getItem
将返回null,而您对空字符串执行严格的相等检查。
替换
if (localStorage.getItem("userID") === "")
与
if (!localStorage.getItem("userID"))
答案 1 :(得分:0)
如果脚本标签在页面底部,则不需要window.onload = checkUser;所以删除它。 将加载程序放在函数的开头,检查userID是否存在,如果它不能使用户保持登录/注册状态,请导航到主页。
答案 2 :(得分:0)
您可以通过它进行检查。
if ("userId" in localStorage) {
alert('yes');
} else {
alert('no');
}
答案 3 :(得分:-1)
localStorage.getItem("toto")
如果找不到密钥,则返回null,因此您应该检查null而不是空字符串
答案 4 :(得分:-1)
if(!localStorage.getItem("userID")){
}
为我工作