$(document).ready(function() {
    // #login-box password field
    $('#password').attr('type', 'text');
    $('#password').val('Password');
});

这是为了将password类型的#password输入字段(id="password")更改为普通的文本字段,然后填充文本"password"。

但这并不奏效。为什么?

表格如下:

<form enctype="application/x-www-form-urlencoded" method="post" action="/auth/sign-in">
  <ol>
    <li>
      <div class="element">
        <input type="text" name="username" id="username" value="Prihlasovacie meno" class="input-text" />
      </div>
    </li>
    <li>
      <div class="element">
        <input type="password" name="password" id="password" value="" class="input-text" />
      </div>
    </li>
    <li class="button">
      <div class="button">
        <input type="submit" name="sign_in" id="sign_in" value="Prihlásiť" class="input-submit" />
      </div>
    </li>
  </ol>
</form>

当前回答

我猜你可以使用一个包含单词“password”的background-image,并在.focus()上将其更改为空的background-image。

.blur() ----> image with "password"

.focus() ----->图像没有“密码”

你也可以用一些CSS和jQuery来实现。有一个文本字段显示在密码字段的顶部,hide()是在focus()和聚焦在密码字段…

其他回答

你试过使用.prop()吗?

$("#password").prop('type','text');

http://api.jquery.com/prop/

一步解决方案

$('#password').get(0).type = 'text';

这样工作起来更容易:

document.querySelector('input[type=password]').setAttribute('type', 'text');

为了再次将其转回password字段,(假设password字段是带有文本类型的第二个输入标记):

document.querySelectorAll('input[type=text]')[1].setAttribute('type', 'password')
jQuery.fn.outerHTML = function() {
    return $(this).clone().wrap('<div>').parent().html();
};
$('input#password').replaceWith($('input.password').outerHTML().replace(/text/g,'password'));

我已经创建了一个jQuery扩展之间切换文本和密码。适用于IE8(可能也适用于ie6和ie7,但没有测试),不会丢失你的值或属性:

$.fn.togglePassword = function (showPass) {
    return this.each(function () {
        var $this = $(this);
        if ($this.attr('type') == 'text' || $this.attr('type') == 'password') {
            var clone = null;
            if((showPass == null && ($this.attr('type') == 'text')) || (showPass != null && !showPass)) {
                clone = $('<input type="password" />');
            }else if((showPass == null && ($this.attr('type') == 'password')) || (showPass != null && showPass)){
                clone = $('<input type="text" />');
            }
            $.each($this.prop("attributes"), function() {
                if(this.name != 'type') {
                    clone.attr(this.name, this.value);
                }
            });
            clone.val($this.val());
            $this.replaceWith(clone);
        }
    });
};

效果非常好。你可以简单地调用$('#element').togglePassword();在两者之间切换或给出一个选项来“强制”基于其他东西(如复选框)的动作:$('#element').togglePassword($checkbox.prop('checked'));