jQuery:如何切换1个输入字段的密码?

时间:2018-10-11 17:56:07

标签: javascript jquery

目前,我在应用程序的2个不同区域中都有我的HTML,可以为2个不同的输入字段切换类.icon-eye-open.icon-eye-close

问题是当用户只需要显示一个输入字段时,当用户单击.icon-eye-close按钮时,两个输入字段都会显示密码。

侧面说明:输入字段是在python中生成的。

执行此操作的最佳方法是什么?

HTML:

<button type="button" class="show-password-toggle icon-eye-close icon-align-confirm"></button>

JS:

$('.show-password-toggle').each(function () {
    var eye = $(this);
    eye.on('click', function() {
        eye.toggleClass("icon-eye-open icon-eye-close");
        eye.siblings("input").each(function () {
            if (eye.hasClass('icon-eye-open')) {
                $(this).attr('type', 'text');
            }
            else if (eye.hasClass('icon-eye-close')) {
                $(this).attr('type', 'password');
            }
        });
    });
});

生成的python代码: <input type="text" name="password2" minlength="6" placeholder="Confirm password" id="id_password2">
<input type="text" name="password2" minlength="6" placeholder="Confirm password" id="id_password2">

谢谢

1 个答案:

答案 0 :(得分:1)

您正在使用each来迭代匹配的输入,所以,是的,您正在为两个输入都这样做。

您可以简单地将它们分开,所以它们不再是兄弟姐妹。例如:

<div>
  <button type="button" class="show-password-toggle icon-eye-close icon-align-confirm">aaa</button>
  <input type="text" value="bbb">
</div>
<div>
  <button type="button" class="show-password-toggle icon-eye-close icon-align-confirm">bbb</button>
  <input type="text" value="bbb">
</div>

或者,使用更具体的选择器,例如id

/*
This is the exact same JS used by the OP
*/

$('.show-password-toggle').each(function () {
    var eye = $(this);
    eye.on('click', function() {
        eye.toggleClass("icon-eye-open icon-eye-close");
        eye.siblings("input").each(function () {
            if (eye.hasClass('icon-eye-open')) {
                $(this).attr('type', 'text');
            }
            else if (eye.hasClass('icon-eye-close')) {
                $(this).attr('type', 'password');
            }
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button type="button" class="show-password-toggle icon-eye-close icon-align-confirm">Toggle first</button>
  <input type="password" value="bbb">
</div>
<div>
  <button type="button" class="show-password-toggle icon-eye-close icon-align-confirm">Toggle second</button>
  <input type="password" value="bbb">
</div>