多密码输入框显示/隐藏切换功能失效,JavaScript遍历逻辑问题排查
代码问题排查
Experiment 1错误点
你获取targetInput时直接读取了type属性的字符串值,而非保留input元素本身,字符串不存在type属性可供修改,因此无法切换输入框类型。
Experiment 2错误点
点击单个图标时遍历了所有密码输入框,会触发所有输入框同时切换显隐,不符合单个控制的需求。
修正后代码
const icons = document.querySelectorAll('i.password'); icons.forEach(function (icon) { icon.addEventListener('click', function () { // 取当前图标对应的输入框,天然一一对应 const targetInput = this.previousElementSibling; if (targetInput.type === 'password') { targetInput.type = 'text'; this.classList.replace('fa-eye-slash', 'fa-eye'); } else { targetInput.type = 'password'; this.classList.replace('fa-eye', 'fa-eye-slash'); } }); });
补充说明
如果后续调整HTML结构,图标和输入框不再是紧邻的兄弟元素,可以将获取targetInput的逻辑替换为:
const targetInput = this.closest('.form-group').querySelector('.show-hide-password');
该写法不受元素层级位置影响,兼容性更强。
内容的提问来源于stack exchange,提问作者Tom-Cat
相关产品推荐
相关产品推荐

