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

时间:2018-07-27 07:14:37

标签: javascript 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>

5 个答案:

答案 0 :(得分:4)

您的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"/>

答案 1 :(得分:4)

您必须从.attr("type");中删除变量var input = $("#pass_log_id").attr("type");
您也可以使用ternary operatortype 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>

答案 2 :(得分:1)

<input type="checkbox" onclick="myFunction()">Show <input type="password" id="myInput" value="Password">


<script>
  function myFunction() {
    var x = document.getElementById("myInput");
    if (x.type === "password") {
      x.type = "text";
    } else {
      x.type = "password";
    }
  }
</script>

答案 3 :(得分:0)

HTML代码

<input type="password" placeholder="Password" id="pwd" class="masked" name="password" 
/>
<button type="button" onclick="showHide()" id="eye">
   <img src="eye.png" alt="eye"/>
 </button>

jquery代码

$(document).ready(function () {
    $("#eye").click(function () {
        if ($("#password").attr("type") === "password") {
            $("#password").attr("type", "text");
        } else {
            $("#password").attr("type", "password");
        }
    });
});

答案 4 :(得分:-1)

请替换

  

var input = $(“#pass_log_id”)。attr(“ type”);

使用

  
    

var input = $(“#pass_log_id”);

  

您需要元素而不是属性