带有显示/隐藏按钮的多个密码字段

时间:2017-08-08 20:04:58

标签: jquery html

我有几个密码输入,但希望通过图标(按钮)切换密码可见性。但是,以下内容会切换所有这些内容,并仅将图标放在第一个上。

这是一个小提琴: https://jsfiddle.net/bu6ysgsj/

  
    $(function() {
        $('.password-group').find('.password-box').each(function(index, input) {
            var $input = $(input);
            $('.password-visibility').click(function() {
                var change = "";
                if ($(this).find('i').hasClass('fa-eye')) {
                    $(this).find('i').removeClass('fa-eye')
                    $(this).find('i').addClass('fa-eye-slash')
                    change = "text";
                } else {
                    $(this).find('i').removeClass('fa-eye-slash')
                    $(this).find('i').addClass('fa-eye')
                    change = "password";
                }
                var rep = $("<input type='" + change + "' />")
                    .attr('id', $input.attr('id'))
                    .attr('name', $input.attr('name'))
                    .attr('class', $input.attr('class'))
                    .val($input.val())
                    .insertBefore($input);
                $input.remove();
                $input = rep;
            }).insertAfter($input);
        });
    });
.password-group {
    position: relative;
    width: 300px;
}

.password-group > input {
    width: 100%;
}

.password-visibility {
    position: absolute;
    right: 8px;
    top: 2px;
}
   
<div class="password-group">
    <input type="password" class="form-control password-box" aria-label="password" value="wdocechoiwceh98">
    <a href="#!" class="password-visibility"><i class="fa fa-eye"></i></a>
</div>
<div class="password-group">
    <input type="password" class="form-control password-box" aria-label="password" value="wdocechoiwceh98">
    <a href="#!" class="password-visibility"><i class="fa fa-eye"></i></a>
</div>
<div class="password-group">
    <input type="password" class="form-control password-box" aria-label="password" value="wdocechoiwceh98">
    <a href="#!" class="password-visibility"><i class="fa fa-eye"></i></a>
</div>
<div class="password-group">
    <input type="password" class="form-control password-box" aria-label="password" value="wdocechoiwceh98">
    <a href="#!" class="password-visibility"><i class="fa fa-eye"></i></a>
</div>
     

1 个答案:

答案 0 :(得分:4)

单击处理程序选择器过于宽泛。

更改

$('.password-visibility').click(function() { ... })

$input.parent().find('.password-visibility').click(function() { ... })

JSFiddle演示:https://jsfiddle.net/bu6ysgsj/1/