繁体   English   中英

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

[英]jquery: How do I toggle password for 1 input field?

目前,我在应用程序的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">

谢谢

您正在使用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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM