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
相关产品推荐
相关产品推荐

