使用jquery单击眼睛图标时如何显示和隐藏密码

新手上路,请多包涵

我需要在单击眼睛图标时显示和隐藏用户密码,所以我为此编写了脚本,当我单击眼睛图标时,只有类正在更改但密码不可见,再次单击斜线眼睛图标它应该隐藏这两个方法不起作用如何解决这个问题?

 <input type="password" name="player_password" id="pass_log_id" />

<span toggle="#password-field" class="fa fa-fw fa-eye field_icon toggle-password"></span>

<script>
$("body").on('click','.toggle-password',function(){
    $(this).toggleClass("fa-eye fa-eye-slash");

    var input = $("#pass_log_id").attr("type");

    if (input.attr("type") === "password") {
        input.attr("type", "text");
    } else {
        input.attr("type", "password");
    }
});
</script>

原文由 Anonymous 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 745
2 个回答

你的 input 实际上是字符串。检查控制台,您应该看到字符串没有方法 attr() 因为您将 $().attr() 分配给 input

 $("body").on('click', '.toggle-password', function() {
  $(this).toggleClass("fa-eye fa-eye-slash");
  var input = $("#pass_log_id");
  if (input.attr("type") === "password") {
    input.attr("type", "text");
  } else {
    input.attr("type", "password");
  }

});
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span toggle="#password-field" class="fa fa-fw fa-eye field_icon toggle-password">Show/Hide</span>
<input type="password" id="pass_log_id"/>

原文由 Justinas 发布,翻译遵循 CC BY-SA 4.0 许可协议

您必须从 --- 中删除 var .attr("type"); var input = $("#pass_log_id").attr("type");

您还可以使用 ternary operator 来更优雅地在 type textpassword 之间切换:

 $(document).on('click', '.toggle-password', function() {

    $(this).toggleClass("fa-eye fa-eye-slash");

    var input = $("#pass_log_id");
    input.attr('type') === 'password' ? input.attr('type','text') : input.attr('type','password')
});
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />

<body>
<input id="pass_log_id" type="password" name="pass" value="MySecretPass">
<span toggle="#password-field" class="fa fa-fw fa-eye field_icon toggle-password"></span>

</body>

原文由 SilverSurfer 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题