Web开发作业登录功能异常:正确账号密码仍提示无效
问题解决:登录验证始终提示无效凭据
核心问题分析
- 你直接把
document.getElementById("docuser")返回的DOM元素对象和字符串"doc1"做比较,两者类型完全不同,永远不会相等,这是验证失败的根本原因。必须获取输入框的.value属性才能拿到用户输入的实际内容。 - 表单默认提交行为会刷新页面,即便验证成功,提示弹窗也可能因页面刷新无法正常显示,需要在事件处理函数中阻止默认提交行为。
修正后的代码
JavaScript代码
function docauth(event) { // 阻止表单默认提交,避免页面刷新 event.preventDefault(); const DU = "doc1"; const DP = "pass1"; // 获取输入框的实际输入值,而非DOM元素本身 const inputUser = document.getElementById("docuser").value; const inputPass = document.getElementById("docpass").value; if(inputUser === DU && inputPass === DP) { alert("login success!"); // 若需要提交表单,可在此处手动调用:document.getElementById("docLOG").submit(); } else { alert("invalid username or password"); } }
HTML代码(仅优化密码输入框类型)
<head> <title>Doctor page</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <fieldset> <legend>doctor login</legend> <form id="docLOG" onsubmit="docauth(event)"> <label for="docuser">Username:</label> <input type="text" id="docuser" name="docuser" required><br><br> <label for="docpass">Password:</label> <!-- 把密码输入框类型改成password,隐藏输入内容更安全 --> <input type="password" id="docpass" name="docpass" required><br><br> <input type="submit" value="Login"> </form> </fieldset> </body> </html>
内容的提问来源于stack exchange,提问作者THE SKULL REAPER
相关产品推荐
相关产品推荐

