You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击Show Password仅第4个password字段正常,前3个切换后密码不可见

问题排查与解决

你的问题核心出在HTML元素的ID命名规范上:

  • HTML4规范要求ID必须以字母(A-Z/a-z)开头,后续可跟字母、数字、下划线等字符;虽然HTML5放宽了限制允许数字开头,但部分浏览器在兼容模式下,对纯数字ID的getElementById解析会出现异常,导致输入框类型切换后无法正常显示内容。
  • 你代码里正常工作的字段id="mutatePasswdField"是字母开头,符合所有规范;而异常的id="2"、id="1"都是纯数字ID,id="password7"虽为字母开头,但如果页面使用HTML4 DOCTYPE,也可能因隐性兼容问题出错。

修复方案

1. 修改ID为合规命名

把所有输入框的ID改成字母开头,同时对应复选框的函数参数:

<p>
<input type="password" name="psw2" id="psw2"><br><br>
<input type="checkbox" name="showPassword3" onclick="myFunction2('psw2')">Show Password
</p>
<br>
working and original field<br>
<input type="password" name="psw3" id="mutatePasswdField"><br>
    <input type="checkbox" name="showPassword4" onclick="myFunction2('mutatePasswdField')">Show Password
<br>
<input type="password" name="psw4" id="psw4"><br>
        <input type="checkbox" name="showPassword5" onclick="myFunction2('psw4')">Show Password
<br>
<input type="password" name="psw5" id="psw5"><br>
<input type="checkbox" name="showPassword6" onclick="myFunction2('psw5')">Show Password

<script>
function myFunction2(id) {
  var y = document.getElementById(id);
  if (y.type === "password") {
    y.type = "text";
  } else {
    y.type = "password";
  }
}
</script>

2. 更优雅的事件绑定方式(推荐)

避免内联onclick,用事件委托实现复用,代码更简洁且易维护:

<p>
<input type="password" name="psw2" id="psw2"><br><br>
<input type="checkbox" name="showPassword3" data-target="psw2">Show Password
</p>
<br>
working and original field<br>
<input type="password" name="psw3" id="mutatePasswdField"><br>
    <input type="checkbox" name="showPassword4" data-target="mutatePasswdField">Show Password
<br>
<input type="password" name="psw4" id="psw4"><br>
        <input type="checkbox" name="showPassword5" data-target="psw4">Show Password
<br>
<input type="password" name="psw5" id="psw5"><br>
<input type="checkbox" name="showPassword6" data-target="psw5">Show Password

<script>
document.addEventListener('change', function(e) {
  // 只处理密码显示复选框的变化
  if (e.target.type === 'checkbox' && e.target.dataset.target) {
    const input = document.getElementById(e.target.dataset.target);
    if (input) {
      // 根据复选框状态切换输入框类型
      input.type = e.target.checked ? 'text' : 'password';
    }
  }
});
</script>

内容的提问来源于stack exchange,提问作者Divya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 19:13:10