使用jQuery更改输入字段的类型(文本 - >密码)

use*_*705 11 html jquery types input

我正在尝试更改输入类型,特别是在点击输入更改type ="text"以更改="密码"之后.

我不知道为什么,但我不能添加选项type ="password"作为输入的属性.

        $('input#id_reg_pass').removeAttr("type"); #this works, type="text" is removing
        $('input#id_reg_pass').attr('type', 'password'); #problem, this not works
        $(this).addClass('exampleText').val($(this).attr('title'));
Run Code Online (Sandbox Code Playgroud)

有没有类似的问题?我很高兴每一个提示......谢谢

kar*_*m79 13

如果您使用的是jQuery 1.6,请.prop改用:

$('input#id_reg_pass').removeAttr("type");
$('input#id_reg_pass').prop('type', 'password');
$(this).addClass('exampleText').val($(this).attr('title'));
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/z8Rj3/


Nik*_*las 6

你可以不改变属性type,如果你想让它发挥作用以同样的方式在所有浏览器,看到添加元素的DOM后,这个这个.

从Microsoft Internet Explorer 5开始,type属性是read/write-once,但仅在使用createElement方法创建输入元素时以及在将其添加到文档之前.


小智 5

我有完全相同的问题,我想在密码字段中显示一个文本,直到用户点击它为止.我做了另一种方法,而不是试图改变我隐藏它的字段的类型并显示一个新的文本字段,然后调用focus().它工作正常.

$("#password_fake").focus(){
    $(this).hide();
    $("#password").show().focus();
}
Run Code Online (Sandbox Code Playgroud)

其中#password_fake是一个文本字段,#password是一个密码字段,其中style ="display:none".