我要求在单击眼睛图标时显示和隐藏用户密码,因此我为此编写了脚本,当我单击眼睛图标时,只有类正在更改,但密码不可见,然后再次单击斜线图标,则应将这两个都隐藏方法不起作用怎么解决这个问题?
<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>
Run Code Online (Sandbox Code Playgroud)
你必须删除变种.attr("type");从您的var input = $("#pass_log_id").attr("type");。
您还可以通过ternary operator在type text和之间切换来使其更优雅password:
$(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')
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
您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");
}
});Run Code Online (Sandbox Code Playgroud)
<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"/>Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)