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

Vanilla JS固定账号密码登录验证功能实现问题求助

固定账号密码验证系统修复方案

问题分析

你的代码存在几个关键错误,导致验证逻辑失效:

  • 条件判断误用赋值运算符=,而非相等比较运算符===
  • 未获取输入框的实际值,直接用DOM元素进行比较
  • 仅验证用户名,未校验密码
  • 表单内的按钮点击会触发默认提交行为,导致页面刷新
  • 密码输入框使用type="text",不符合安全规范

修正后的代码

HTML部分

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Project Keypad</title>
  <link rel="stylesheet" href="css/style.css">
</head>
<body class="light-mode">
  <button onclick="myFunction()" id="toggle-button">☀️</button>
  <h2> Welcome to Project Keypad</h2>
  <form id="loginForm">
    <div id="login">
      Enter Username: <input type="text" id="userName" placeholder="Enter username here">
      <br><br>
      Enter Password: <input type="password" id="enterPassword" placeholder="Enter password here">
      <br><br>
      <input type="reset">
      <button type="submit">Log In</button>
    </div>
  </form>

  <script src="js/script.js"></script>
  <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>
  <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script>
</body>
<footer></footer>
</html>

JS部分(script.js)

const correctUser = 'keypaduser';
const correctPassword = 'animal123';
const loginForm = document.getElementById('loginForm');

loginForm.addEventListener('submit', function(e) {
  // 阻止表单默认提交行为
  e.preventDefault();
  
  const inputUser = document.getElementById('userName').value;
  const inputPassword = document.getElementById('enterPassword').value;

  if (inputUser === correctUser && inputPassword === correctPassword) {
    alert("Thank you for Login & Redirecting you to Home Page!");
    window.location = "homepage.html";
  } else {
    alert("Username or Password Incorrect!");
  }
});

关键修改说明

  • 将密码输入框改为type="password",隐藏输入内容
  • 给表单添加ID,通过事件监听处理提交逻辑,避免内联onclick
  • 使用e.preventDefault()阻止表单默认刷新行为
  • 获取输入框的.value属性进行值比较
  • 同时校验用户名和密码,符合需求逻辑
  • 使用===严格相等运算符,避免类型转换导致的错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:45:00