JS 动态修改 input 的 type 属性

来源:互联网 发布:国家知识产权局知乎 编辑:程序博客网 时间:2024/06/05 07:03

很久没来部落格了,杂草丛生广告横行啊!工作比以前轻松很多人却越来越懒了…… 最近做一个登陆框,当鼠标焦点放在两个输入框上面的时候将输入框置空,简单说就是清除输入框的默认值,如图

这里写了一个jQuery对象方法的插件

  1. (function($) {   
  2.     jQuery.fn.extend({   
  3.         “clearDefault”:function(className){   
  4.             $(this).focus(function(){   
  5.                 if (className) {   
  6.                     $(this).addClass(className);   
  7.                 }   
  8.                 if($(this).val() ==this.defaultValue){   
  9.                     $(this).val(“”);   
  10.                 }   
  11.             }).blur(function(){   
  12.                 if (className) {   
  13.                     $(this).removeClass(className);   
  14.                 }   
  15.                 if ($(this).val() == ) {   
  16.                     $(this).val(this.defaultValue);   
  17.                 }   
  18.             });   
  19.         }   
  20.     });   
  21. })(jQuery);  

调用: $(“#uname”); 可选参数class为获取焦点时input的class,但是清除密码的时候出了一个问题,用户输入的密码应该是 ”*****” ,这里需要将input 的type 属性由 text 换成 password ,如果用户没有输入密码,鼠标失去焦点的时候 type 换回 text ,value 值为 “密码”。

  1. $(“#pswd”).focus(function(){   
  2.     $(this).attr(‘type’,'password’);  

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

  1. // We can’t allow the type property to be changed (since it causes problems in IE)  
  2. if ( name === “type” && rtype.test( elem.nodeName ) && elem.parentNode ) {   
  3.     jQuery.error( “type property can’t be changed” );  

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

  1. $(“#pwd”).focus(function(){   
  2.     $(“#pwd”)[0].type = ’password’;   
  3.     $(“#pwd”).val(“”);   
  4. });  

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

  1. $(“#pwd”).focus(function(){   
  2.     alert($(“#pwd”)[0].type);   
  3.     $(“#pwd”)[0].type = ’password’;   
  4.     $(“#pwd”).val(“”);   
  5. });  

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

  1. $(“#pwd”).focus(function(){   
  2.     $(“#pwd”).remove();   
  3.     $(“body”).append(‘<input id=“pwd” name=“pwd” type=“password” />’);   
  4.     $(“#pwd”).focus(); // 焦点转移  
  5. });  

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

  1. <input id=“showPwd” class=“txt” type=“text” value=“密码” tabindex=“2″ />   
  2. <input id=“pwd” class=“txt” name=“password” type=“password” />   
  3. var showPwd = $(“#showPwd”), pwd = $(“#pwd”);   
  4. showPwd.focus(function(){   
  5.     pwd.show().focus();   
  6.     showPwd.hide();   
  7. });   
  8. pwd.blur(function(){   
  9.     if(pwd.val()==“”) {   
  10.         showPwd.show();   
  11.         pwd.hide();   
  12.     }   
  13. });  

完美解决。