jQuery密码可见性切换仅部分生效,求排查问题
问题原因分析
你的代码核心问题出在选择器匹配逻辑上:
- 首次点击时,
$(this).closest('form').find('input[type=password]')能找到所有密码输入框,将它们的type改为text; - 再次点击时,这些输入框的
type已经变为text,input[type=password]选择器匹配不到任何元素,自然无法把type改回password。
修复方案
方案1:提前缓存目标输入框
提前获取表单内所有初始为密码类型的输入框,避免每次点击依赖type属性查找:
// 提前缓存表单内的密码输入框 const passwordInputs = $('#toggle_pw_vis').closest('form').find('input[type=password]'); $('#toggle_pw_vis').click(function () { const isChecked = $(this).is(':checked'); passwordInputs.attr('type', isChecked ? 'text' : 'password'); });
方案2:用自定义类标识密码框
给所有密码输入框添加自定义类,通过类选择器定位,不受type属性变化影响:
<!-- 给密码输入框添加自定义类 --> <input type="password" class="password-input"> <input type="password" class="password-input">
$('#toggle_pw_vis').click(function () { const isChecked = $(this).is(':checked'); $(this).closest('form').find('.password-input').attr('type', isChecked ? 'text' : 'password'); });
方案3:兼容严格浏览器的替代方案
部分浏览器限制动态修改input的type属性,可通过切换两个输入框的显示状态实现:
<!-- 每个密码框对应一个文本输入框,默认隐藏文本框 --> <input type="password" class="pw-original"> <input type="text" class="pw-copy" style="display: none;">
$('#toggle_pw_vis').click(function () { const isChecked = $(this).is(':checked'); const $form = $(this).closest('form'); // 切换显示状态 $form.find('.pw-original').toggle(!isChecked); $form.find('.pw-copy').toggle(isChecked); // 同步输入内容 if (isChecked) { $form.find('.pw-copy').val($form.find('.pw-original').val()); } else { $form.find('.pw-original').val($form.find('.pw-copy').val()); } });
内容的提问来源于stack exchange,提问作者JoshBali
相关产品推荐
相关产品推荐

