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

含@的邮箱登录后window.location无法跳转,纯字符输入正常

登录跳转异常问题排查

问题描述

开发登录界面时,输入含@的邮箱登录,执行到window.location语句却无法跳转;输入纯字母内容则跳转正常。相关代码片段如下:

HTML代码

<div class="input-field">
  <input type="email" id="userName" placeholder="Email" required>
</div>

...

<div class="action">
  <button onclick="check()">Sign in</button>
</div>

JS代码

function check(){
   
    var name= document.getElementById('userName').value;
    var pw = document.getElementById('userPw').value;
    
    var userObjectString = window.localStorage.getItem(userName);
    
    if (!userObjectString) {
        alert('Error on login');
    } else {
        var user = JSON.parse(userObjectString);
        if(name == user.name && pw == user.pw){
            alert('You are logged in.');
            window.location = "./user.html";
        } else {
            alert('Error on login');
        }
    }
}

错误原因及解决方法

1. 按钮默认触发表单提交,打断跳转

你的按钮未指定type="button",默认类型是submit。如果按钮包裹在<form>标签内:

  • 输入带@的邮箱时,符合type="email"的格式验证,浏览器允许表单提交,页面刷新会直接覆盖window.location的跳转行为;
  • 输入纯字母时,不符合邮箱格式,浏览器阻止表单提交,window.location才能正常生效。

解决方法:给按钮添加type="button"属性,避免触发表单提交:

<button type="button" onclick="check()">Sign in</button>

2. localStorage取值时变量名错误

JS代码中,你定义的输入值变量是name,但调用localStorage.getItem()时用了未定义的userName,这会导致取到键为"undefined"的存储值(localStorage键会自动转为字符串)。只有当你之前恰好把用户信息存在这个错误的键下时,纯字母输入才能匹配成功,属于偶然情况。

解决方法:把getItem的参数改为正确的变量name:

var userObjectString = window.localStorage.getItem(name);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 02:03:59