You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法清除sessionStorage?纯JS登录表单会话数据问题求助

问题分析与修复方案

核心问题点

  • isAuthorised 初始化错误:window.sessionStorage.key("authorised") 是用来获取指定索引位置的键名,而非键对应的值,正确写法应为 sessionStorage.getItem('authorised')。
  • setInterval 中的赋值逻辑错误:if (isAuthorised = true) 是赋值操作,会永远返回真,应改为判断相等的 ===;且每次检查时需重新从 sessionStorage 获取最新状态,因为变量不会自动同步存储值的变化。
  • 登出后未同步变量状态:清除 sessionStorage 后未更新 isAuthorised 变量,导致检查逻辑仍使用旧值。
  • 冗余的登出操作:先设置 authorised 为 false 再移除键,二选一即可,移除键的方式更直接。

修复后的代码

// 初始化授权状态,从sessionStorage获取,不存在则为false
var isAuthorised = sessionStorage.getItem('authorised') === 'true';

var available_user_name = ["user1", "user2", "user3"],
    available_user_pass = ["1001", "2002", "3003"],
    UAP = $("#userNameAndPassword");

// 渲染可用账户
for (var i = 0; i < available_user_name.length; i++) {
    var user_names = available_user_name[i];
    var user_passws = available_user_pass[i];
    $("#available_accounts").append(`<div><div>${user_names}</div><div>${user_passws}</div></div>`);
}

// 登录按钮点击事件
$("#btn").click(function () {
    var user_name = document.getElementById("email").value;
    var user_pass = document.getElementById("pwd1").value;
    var result = $("#result");

    if ($.inArray(user_name, available_user_name) >= 0) {
        var userIndex = available_user_name.indexOf(user_name);
        // 直接用索引匹配密码,比两次indexOf更可靠
        if (available_user_pass[userIndex] === user_pass) {
            result.html(`Welcome back : ${user_name}`).css("color", "SeaGreen");
            sessionStorage.setItem('authorised', 'true');
            // 登录成功后同步变量
            isAuthorised = true;
        } else {
            result.html("You've selected wrong password for username, please try again").css("color", "crimson");
        }
    } else {
        result.html("This name doesn't registred with us").css("color", "crimson");
    }
});

// 状态检查定时器
setInterval(function check() {
    // 每次检查都从sessionStorage获取最新值,确保同步
    isAuthorised = sessionStorage.getItem('authorised') === 'true';
    
    if (isAuthorised) {
        $(".login-wrapper").delay(500).fadeOut(500).removeClass("flex");
        $(".secure-content-wrapper").delay(500).fadeIn(500);
    } else {
        $(".login-wrapper").fadeIn(500).addClass("flex");
        $(".secure-content-wrapper").fadeOut(500);
    }
}, 200);

// 登出按钮点击事件
$(".logout").click(function (e) {
    // 移除授权状态键
    sessionStorage.removeItem('authorised');
    // 同步变量状态
    isAuthorised = false;
    console.log(isAuthorised);
});

关于你偏好的简洁写法说明

如果想用 sessionStorage['authorised'] = true 这种写法,需要注意:

  • sessionStorage 只能存储字符串,true 会被自动转为 "true",读取时要做字符串比较:sessionStorage['authorised'] === 'true'
  • 登出时直接移除键即可:delete sessionStorage['authorised'],或者设置为 "false",之后读取时判断是否等于 "true"

内容的提问来源于stack exchange,提问作者Noel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 12:25:30