显示密码图标

时间:2019-11-26 11:43:37

标签: jquery html

我有这个HTML ...

<div class="signin-form-label-group">
        <input type="password" id="password" name="password" class="form-control"
               placeholder="Password"
               required>
        <label for="password">Password</label>
        <span toggle="#password" class="mdi mdi-eye-off toggle-password"></span>
      </div>

还有这个jQuery:

$(".toggle-password").click(function() {
      $(this).toggleClass("mdi mdi-eye");
      var input = $($(this).attr("toggle"));
      input.type === "password" ? input.type = "text" : input.type = "password";
    });

我正在使用材料设计图标。问题是,单击“开眼”图标时,会显示文本,但该图标不会仅变为眼睛。有什么办法解决吗?

编辑:我发现问题实际上是... 默认情况下,该类具有class="mdi-eye-off toggle-password mdi"。当点击眼睛时,就会发生这种情况... class="mdi-eye-off toggle-password mdi-eye" 当然,由于切换类别,mdi-eye-off应该已经被删除。但是还没有。为什么?该怎么解决?

2 个答案:

答案 0 :(得分:1)

使用像这样显示密码HTML

<div class="signin-form-label-group">
    <input type="password" id="password" name="password" class="form-control"
           placeholder="Password"
           required>
    <label for="password">Password</label>
    <span toggle="#password" class="mdi mdi-eye-off toggle-password" onclick="myFunction(this)">Eye</span>
</div>

<script>
    function myFunction(e) {

      var x = document.getElementById("password");
      if (x.type === "password") {
          e.classList.add('mdi-eye')
        e.classList.remove('mdi-eye-off')
        x.type = "text";
      } else {
          e.classList.add('mdi-eye-off')
        e.classList.remove('mdi-eye')
        x.type = "password";
      }
    }
</script>

答案 1 :(得分:0)

尝试使用此jQuery。

$(".toggle-password").on('click', function() {
    $(this).toggleClass("your-toggle-class");
    var input = $("#password");
    if (input.attr("type") === "password") {
        input.attr("type", "text");
    } else {
        input.attr("type", "password");
    }

});