Javascript 在显示和隐藏密码之间切换
Javascript toggle between show and hide a password
我一直在做一个项目,需要我在密码字段中切换显示和隐藏密码。
我想出的JS代码是:
<script>
function text(item) {
if (document.getElementById('password').type = "password") {
document.getElementById('password').type = "text";
} else {
document.getElementById('password').type = "password";
}
}
</script>
<input type="checkbox" id="logon-show-password" name="showpassword" class="tickable" onclick="text(this)">
<input type="password" id="password" />
出于某种原因,它在密码 -> 文本之间切换时工作正常,但无法执行相反的操作。
我做错了什么?
您在 if 条件
中缺少 =
if(document.getElementById('password').type="password"){
^^^^
应该是
if(document.getElementById('password').type=="password"){
否则它会将类型密码分配给该字段并且它将 return 始终为 true
function text(item) {
if (document.getElementById('password').type == "password") {
document.getElementById('password').type = "text";
} else {
document.getElementById('password').type = "password";
}
}
<input type="checkbox" id="logon-show-password" name="showpassword" class="tickable" onclick="text(this)">
<input id="password" type="password" />
我一直在做一个项目,需要我在密码字段中切换显示和隐藏密码。
我想出的JS代码是:
<script>
function text(item) {
if (document.getElementById('password').type = "password") {
document.getElementById('password').type = "text";
} else {
document.getElementById('password').type = "password";
}
}
</script>
<input type="checkbox" id="logon-show-password" name="showpassword" class="tickable" onclick="text(this)">
<input type="password" id="password" />
出于某种原因,它在密码 -> 文本之间切换时工作正常,但无法执行相反的操作。
我做错了什么?
您在 if 条件
中缺少=
if(document.getElementById('password').type="password"){
^^^^
应该是
if(document.getElementById('password').type=="password"){
否则它会将类型密码分配给该字段并且它将 return 始终为 true
function text(item) {
if (document.getElementById('password').type == "password") {
document.getElementById('password').type = "text";
} else {
document.getElementById('password').type = "password";
}
}
<input type="checkbox" id="logon-show-password" name="showpassword" class="tickable" onclick="text(this)">
<input id="password" type="password" />