我正在使用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>
答案 0 :(得分:2)
更正您的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>
答案 1 :(得分:1)
请尝试以下操作:
$(document).ready(function(){
$('.1').on('click',function(){
var current_type = $('.password').attr('type');
if(current_type == 'password'){
$('.password').attr('type','text');
}
else{
$('.password').attr('type','password');
}
});
})