【问题标题】:Changing the type of an input field using jQuery (text -> password)使用 jQuery 更改输入字段的类型(文本 -> 密码)
【发布时间】:2011-06-19 12:59:00
【问题描述】:

我正在尝试更改输入的类型,特别是在点击输入后将 type="text" 更改为 change="password"

我不知道为什么,但我不能将选项 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'));

没有人有类似的问题吗?我会为每一个提示感到高兴... 谢谢

【问题讨论】:

标签: jquery html types input


【解决方案1】:

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

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

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

【讨论】:

  • 感谢大家的回复。我正在使用这个tutorial。但即使你帮助我(很高兴),我仍然在为输入类型=“密码”和该输入中的文本而苦苦挣扎……完全可以编辑本教程以输入密码吗?
【解决方案2】:

将元素添加到 DOM 后,您无法更改属性 type,如果您希望它在所有浏览器上以相同的方式运行,请参阅 thisthis

从 Microsoft Internet Explorer 5 开始, type 属性是读/写一次, 但仅当输入元素是 使用 createElement 方法创建 在它被添加到 文件。

【讨论】:

    【解决方案3】:

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

    $("#password_fake").focus(){
        $(this).hide();
        $("#password").show().focus();
    }
    

    其中#password_fake 是一个文本字段,#password 是一个密码字段,样式为“display:none”。

    【讨论】:

    • 这很好,但我得到一个语法错误;你的函数不应该在括号内吗? .focus(function(){ ... });
    【解决方案4】:

    你的代码给我抛出了一个错误,type property can't be changed。不过有趣的是,以下代码至少在 Chrome 上对我有用:

    $('input#id_reg_pass')[0].type = 'password';
    

    这可能是因为它不能跨浏览器工作,这可以解释为什么 jQuery 不允许它(正如 Niklas 所指出的,情况就是这样)。或者,您可以构造一个具有相同属性的新 <input> 并用它替换旧的。

    【讨论】:

    • 检查我的答案。 jQuery 抛出该错误是有原因的,“该异常实际上是由 jQuery 抛出的,因此不是错误,而是让编码人员知道它不起作用的功能。”
    • @niklas:是的,我看到了你的回答。不幸的是,再一次,只有 IE 不能像人们合理预期的那样工作......
    【解决方案5】:

    试试这个demo is here

    $(document).delegate('input[type="text"]','click', function() {
        $(this).replaceWith('<input type="password" value="'+this.value+'" id="'+this.id+'">');
    }); 
    $(document).delegate('input[type="password"]','click', function() {
        $(this).replaceWith('<input type="text" value="'+this.value+'" id="'+this.id+'">');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-24
      • 2014-02-13
      • 2011-11-03
      • 2017-03-09
      • 1970-01-01
      • 2011-12-25
      • 2012-09-27
      • 1970-01-01
      相关资源
      最近更新 更多