如何实现单密码输入框支持多密码跳转对应页面的简易验证页
单输入框多密码跳转实现方案
核心思路是用JS对象存储密码和对应跳转页面的映射关系,替代原来硬编码的单个密码判断,后续扩展新的密码规则只需要改配置,不需要重复写判断逻辑。
修改完成的登录页代码
直接替换你原来的登录页代码即可:
<!DOCTYPE html> <html> <head> <title>Login page</title> </head> <body> <form> <label for="pswd">Enter your password: </label> <input type="password" id="pswd"> <input type="button" value="Submit" onclick="checkPswd();" /> </form> <script type="text/javascript"> function checkPswd() { // 密码-跳转页映射配置:键为用户输入的密码,值为对应页面地址 const passwordRouteMap = { "dogs": "dogs.html", "cats": "cats.html" // 新增规则直接按格式往下加即可,例: // "hamsters": "hamsters.html" } const inputPassword = document.getElementById("pswd").value.trim(); if (passwordRouteMap[inputPassword]) { window.location.href = passwordRouteMap[inputPassword]; } else { alert("Passwords do not match."); } } </script> </body> </html>
其他主题页参考
你现有的dogs.html不需要修改,其他主题页按照相同结构创建即可,比如猫咪主题页cats.html参考代码:
<!DOCTYPE html> <html> <head> <title>Cats page</title> </head> <body> <h1>Welcome!! you entered the CATS password</h1> </body> </html>
注意事项
- 新增密码跳转规则时,不需要修改判断逻辑,只需要在
passwordRouteMap对象中新增对应键值对 - 代码对用户输入做了首尾去空格处理,避免用户误输入前后空格导致匹配失败
- 采用
window.location.href做跳转,兼容所有主流浏览器,不会出现跳转异常
内容的提问来源于stack exchange,提问作者astraytel
相关产品推荐
相关产品推荐

