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

登录验证成功后window.location.href跳转失效,页面回退至登录页求助

问题原因

你的问题出在表单的默认提交行为上:当点击type="submit"的按钮或者按下回车键时,浏览器会自动触发表单提交的默认逻辑,导致页面刷新并回退到原登录页——哪怕登录成功的alert弹出来了,后续的window.location.href跳转也会被这个默认刷新行为打断。

解决方案

下面提供三种简单的修复方式,任选其一即可:

方法1:修改按钮类型为button

直接把按钮的type="submit"改成type="button",这样点击按钮只会执行auth()函数,不会触发表单的默认提交:

<form id="login" class="input-group">
  <input type="text" id="user" class="input-field" placeholder="Username" required>
  <input type="password" id="pass" class="input-field" placeholder="Password" required>
  <input type="checkbox" class="checkbox"><span>Remember Password</span>
  <!-- 将type从submit改为button -->
  <button type="button" class="submit-btn" onclick="auth()">Log in</button>
</form>

方法2:在auth函数中阻止默认事件

给auth函数添加事件参数,调用preventDefault()来阻断表单的默认提交行为:

// 接收event参数
function auth(event) {
  // 阻止表单默认提交逻辑
  event.preventDefault();
  let x = document.getElementById("user").value;
  let y = document.getElementById("pass").value;

  if (x == "admin" && y == "12345") {
    alert("You have successfuly log in")
    window.location.href = "index.html";
  } else {
    alert("Invalid login credentials. Please try again.");
  }
}

同时修改HTML中的onclick,传入事件对象:

<button type="submit" class="submit-btn" onclick="auth(event)">Log in</button>

方法3:给表单绑定onsubmit事件

修改表单的onsubmit属性,让它执行auth函数并返回false,从而阻止默认提交:

<!-- 添加onsubmit事件 -->
<form id="login" class="input-group" onsubmit="return auth()">
  <input type="text" id="user" class="input-field" placeholder="Username" required>
  <input type="password" id="pass" class="input-field" placeholder="Password" required>
  <input type="checkbox" class="checkbox"><span>Remember Password</span>
  <button type="submit" class="submit-btn">Log in</button>
</form>

然后修改JS函数,在最后返回false:

function auth() {
  let x = document.getElementById("user").value;
  let y = document.getElementById("pass").value;

  if (x == "admin" && y == "12345") {
    alert("You have successfuly log in")
    window.location.href = "index.html";
  } else {
    alert("Invalid login credentials. Please try again.");
  }
  // 返回false阻止表单默认提交
  return false;
}
新手小提示

建议你养成用let/const声明变量的习惯,避免全局变量污染:比如把原来的x = ...改成let x = ...,这是前端开发的基础规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:10:47