密码隐藏/显示按钮只能单向工作

Password Hide/Show Button only works one-way

本文关键字:单向工作 按钮 显示 隐藏 密码      更新时间:2023-09-26

我构建了一个小函数,它应该将跨度的内容更改为<td>中,该跨度与按钮一起位于中,在第一次按下按钮时变为按钮的值。再次按下按钮时,它应将内容替换为四个星号。

不幸的是,它只能单向工作

$(".pw_show").click(function () {
  $(this).parent('td').children('span').html($(this).attr('value'));
  $(this).toggleClass('pw_hide pw_show');
});
$(".pw_hide").click(function () {
  $(this).parent('td').children('span').html("****");
  $(this).toggleClass('pw_hide pw_show');
});

在这里摆弄:http://jsfiddle.net/kXNk8/218/

切换类,以便需要将动态事件绑定与 .on() 一起使用,而不是.click()

$('table').on('click',".pw_show", function () {
    $(this).parent('td').children('span').html($(this).attr('value'));
  $(this).toggleClass('pw_hide pw_show');
});
$('table').on('click',".pw_hide", function () {
    $(this).parent('td').children('span').html("****");
  $(this).toggleClass('pw_hide pw_show');
});

js小提琴示例

第一次单击后,导致问题的元素上不再存在.pw_show

使用 .on() 委派给静态元素将使其工作,或者您应该完全更改它。

$(document).on("click", ".pw_show", function () {
  $(this).parent('td').children('span').html($(this).attr('value'));
  $(this).toggleClass('pw_hide pw_show');
});
$(document).on("click", ".pw_hide", function () {
  $(this).parent('td').children('span').html("****");
  $(this).toggleClass('pw_hide pw_show');
});

小提琴:http://jsfiddle.net/4atrmks3/

您实际上应该在passwordtext之间切换type的属性,而不是使用占位符。

var password = false;
$('a').click(function(){
    if (!password){
       password = true;
       $('input').attr('type', 'password');
    } else {
       password = false;
       $('input').attr('type', 'text');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<a href="#">Click to toggle password / text</a>