首页 > 解决方案 > 如果语句有效,但是当我添加 else 时没有任何效果

问题描述

我正在使用 jQuery 进行密码隐藏/显示切换,当我添加两个按钮时,一个用于显示,另一个用于隐藏,一切正常,但我想切换这里的代码

jQuery

$(document).ready(function(){
    $('.1').on('click',function(){
        var pass = $('.password');
        if(pass.attr('type','password')){
            pass.attr('type','text');
        }
        else{
            pass.attr('type','password');
        }
    })
})

HTML

<div id="main">
    <h1>Form</h1>
    Enter your login <input class="login">
    Enter password here <input class="password" type="password">
    <button class="1">Show password</button>
</div>

标签: jquery

解决方案


纠正你if()的情况如下:

if(pass.attr('type') ==='password')){

我会尝试这样做:

function togglePassword(obj) {
  var x = document.getElementById("password");
  if (x.type === "password") {
    x.type = "text";
    $(obj).html('Hide Password');
  } else {
    x.type = "password";
    $(obj).html('Show Password');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="main">
  <h1>Form</h1>
  Enter your login <input class="login"><br>
  <!-- converted  class to id to make it unique -->
  Enter password here <input id="password" type="password"><br>
  <button onclick="togglePassword(this)">Show Password</button>
</div>


推荐阅读