JS 动态修改 input 的 type 属性

来源:互联网 发布:如何学windows api 编辑:程序博客网 时间:2024/05/16 01:41
JS 动态修改 input 的 type 属性
调用: $(“#uname”);可选参数class为获取焦点时input的class,但是清除密码的时候出了一个问题,用户输入的密码应该是 ”*****”,这里需要将input 的type 属性由 text 换成 password ,如果用户没有输入密码,鼠标失去焦点的时候 type换回 text ,value 值为 “密码”。

$("#pswd").focus(function(){   $(this).attr('type','password');});

发现并没有实现预期效果,出现 uncaught exception type property can’t bechanged 错误,查看jQuery 1.42源码 1488 行

// We can't allow the type property to be changed (since itcauses problems in IE)if ( name === "type" &&rtype.test( elem.nodeName ) &&elem.parentNode ) {   jQuery.error( "type property can't be changed");}

 
jQuery 修改不了用源生的JS呢?

$("#pwd").focus(function(){   $("#pwd")[0].type = 'password';   $("#pwd").val("");});

 
发现在FF下可以修改并将密码输入框type 修改为 “password” 并将value设置为空,而IE下却提示无法得到type属性,不支持该命令。 弹出 type 看看真的无法得到吗?

$("#pwd").focus(function(){   alert($("#pwd")[0].type);   $("#pwd")[0].type = 'password';   $("#pwd").val("");});
 
发现弹出text ,原来不是无法得到,只是IE下不能修改。 各种 google后发现input的type属性只能在初始的时候设定却不能修改(IE不能,FF可以,个人认为,不知道是否准确,如有不对请大牛指教)。这样我是否可以先remove然后再生成一个type是password的密码输入框呢?

$("#pwd").focus(function(){   $("#pwd").remove();   $("body").append('<input id="pwd"name="pwd" type="password" />');   $("#pwd").focus(); // 焦点转移);

可以实现,但是输入为空鼠标失去焦点再返回到起始状态的时候不怎么好写,节点生成删除为什么不用两个密码框来显示隐藏呢?

<input id="showPwd" class="txt" type="text" value="密码" tabindex="2" /><input id="pwd" class="txt" name="password" type="password" />

var showPwd = $("#showPwd"), pwd = $("#pwd");showPwd.focus(function(){   pwd.show().focus();   showPwd.hide();});pwd.blur(function(){   if(pwd.val()=="") {       showPwd.show();       pwd.hide();    }});

原创粉丝点击