密码隐藏/显示按钮仅适用于单向

时间:2016-02-07 18:28:36

标签: javascript jquery html

我已经构建了一个小功能,它应该改变跨度的内容,该内容位于<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/

3 个答案:

答案 0 :(得分:2)

您切换了类,因此您需要使用.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');
});

<强> jsFiddle example

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

答案 1 :(得分:1)

使用.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/

答案 2 :(得分:-1)

您应该只在typepassword之间切换text的属性,而不是使用占位符。

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>

相关问题