这是我的HTML表单: -
<input name="inputPassword" type="password" id="inputPassword" placeholder="Password.."><span class="add-on"><i class="icon-eye-open"></i></span>
这是我对Jquery的尝试[我不是Jquery学生:(]
<script type="text/javascript">
$(".icon-eye-open").click(function(){
$('.icon-eye-open').removeClass('icon-eye-open').addClass('icon-eye-close');
document.getElementById("inputPassword").setAttribute('type', 'text');
});
$(".icon-eye-close").click(function(){
$('.icon-eye-close').removeClass('icon-eye-close').addClass('icon-eye-open');
document.getElementById("inputPassword").setAttribute('type', 'password');
});
</script>
所以,你可能已经猜到了,我想做什么。我实际上试图替换点击类的类[在类之间切换]而不是尝试将属性从密码更改为文本,反之亦然。
这不是工作。
这是jsfiddle演示: - http://jsfiddle.net/gR5FH/
你能否建议/帮助我找出错误。
由于
答案 0 :(得分:4)
试试这个
$(".icon-eye-open").on("click", function() {
$(this).toggleClass("icon-eye-close");
var type = $("#inputPassword").attr("type");
if (type == "text")
{ $("#inputPassword").attr("type", "password");}
else
{ $("#inputPassword").attr("type", "text"); }
});
答案 1 :(得分:1)
您的问题是,当您开始侦听$(".icon-eye-close")
事件时,元素click
不存在,因此代码永远不会运行。您可以通过为click
使用唯一的事件处理程序来阻止此操作,然后在其中切换类和输入类型。
试试这个HTML:
<input name="inputPassword" type="password" id="inputPassword" placeholder="Password...">
<span class="add-on">
<i id="visibilitySwitch" class="icon-eye-close"></i>
</span>
有了这个JS:
$("#visibilitySwitch").click(function(){
$(this)
.toggleClass('icon-eye-open')
.toggleClass('icon-eye-close');
if ($('#inputPassword').attr('type') == 'password')
$('#inputPassword').attr('type', 'text')
else
$('#inputPassword').attr('type', 'password')
});