jquery - 如果语句有效,但是当我添加 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>
解决方案
纠正你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>
推荐阅读
- python-3.x - Python 模块因信任而出错
- python - 如何在python中使用groupby更新原始数组
- pdf - 使用 PDFBOX 标记 PDF 时,我无法看到标记下的内容?
- spring - Spring My-batis MapperScannerConfigurer 不解析数据源占位符值
- facebook - facebook graph api 完成视频洞察数据处理多长时间
- python - 找不到满足俳句要求的版本
- git - 如何在旧版本的旧 .tar.gz 存档之上重新构建新代码?
- javascript - Javascript 重置我现有的 CSS 对齐方式
- node.js - 如何将 nvm 与 c-shell 一起使用?
- node.js - 如果存在则附加到嵌套对象,否则在 DynamoDB 中创建新的嵌套对象