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

HTML重复id绑定JavaScript的问题及简便解决方法咨询

解决重复ID导致的密码切换按钮失效问题

简便解决方案:用Class替代ID,利用DOM层级关联元素

首先修正HTML,把重复的ID替换成Class(ID在文档中必须唯一,这是HTML规范):

<div class="txt_field">
  <input type="password" required="" class="password-input">
  <i class="far fa-eye toggle-password"></i>
  <span></span>
  <label>Password</label>
</div>
<div class="txt_field">
  <input type="password" required="" class="password-input">
  <i class="far fa-eye toggle-password"></i>
  <span></span>
  <label>Confirm Password</label>
</div>

然后修改JavaScript,通过元素的DOM层级关系,让每个切换按钮只控制它所在容器内的密码输入框:

// 选中所有切换按钮
const toggleButtons = document.querySelectorAll('.toggle-password');

// 给每个按钮绑定点击事件
toggleButtons.forEach(button => {
  button.addEventListener('click', function() {
    // 找到当前按钮所在的txt_field容器
    const container = this.closest('.txt_field');
    // 在容器内找到对应的密码输入框
    const passwordInput = container.querySelector('.password-input');
    
    // 切换输入框的类型
    const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
    passwordInput.setAttribute('type', type);
    
    // 切换图标样式
    this.classList.toggle('fa-eye-slash');
  });
});

为什么这个方法好用?

  • 不用给每个元素加唯一ID(比如id_password1、id_password2),减少冗余代码
  • 利用closest()方法精准定位当前按钮的父容器,确保操作的是对应输入框,不会干扰其他元素
  • 代码可扩展性强,后续再添加更多密码输入框,不需要修改JS逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:18:37