我有一个显示/隐藏密码按钮,当我单击“显示密码”时,它会起作用,但当我尝试再次隐藏它时,它不会起作用。
fiddle :http://jsfiddle.net/vcvgj09z/
<input type="password" id="pass1" value="Now try to hide me">
<a href="#" id="show-password"><i class="fa fa-eye"></i> Show</a>
$("#show-password").on("click",function() {
$(this).html('<i class="fa fa-eye-slash"></i> Hide');
$(this).prop("id","hide-password");
$("#pass1").attr("type","text");
});
$("#hide-password").on("click",function() {
$(this).html('<i class="fa fa-eye"></i> Show');
$(this).prop("id","show-password");
$("#pass1").attr("type","password");
});
最佳答案
根据我的评论,您的代码不起作用的原因是因为元素 #hide-password
在运行时不存在于 DOM 中,因此 不会绑定(bind)任何点击事件到它。
虽然您可以使用.on()
来监听事件冒泡,但我强烈建议不要更改元素的ID。相反,您可以将切换开/关状态存储为 jQuery data
对象。这种方法的优点是:
- 不依赖于更改标记和事件冒泡
- 通过评估和修改 jQuery
data
对象来存储密码的切换状态 - 允许其他元素操纵/影响切换状态
请参阅此处的 fiddle :http://jsfiddle.net/teddyrised/vcvgj09z/10/
$('#toggle-password').click(function() {
// Check state
if(!$(this).data('state') || $(this).data('state') == 0) {
// If the data object "state" is undefined or have a value of 0, convert password to text
// Update HTML and data object
$(this)
.html('<i class="fa fa-eye-slash"></i> Hide')
.data('state', 1);
// Change password to text
$("#pass1").attr('type', 'text');
} else {
// If the data object "state" has a value of 1, convert text to password
// Update HTML and data object
$(this)
.html('<i class="fa fa-eye"></i> Show')
.data('state', 0);
// Change text to password
$("#pass1").attr("type","password");
}
});
关于javascript - 更改元素 ID 后无法触发操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27321107/