2016-07-07 111 views
0

我使用这两个几乎相同的函数来捕获输入字段中的按键事件,并清除其中的标签。但出于某种原因,我输入的第一个字母不会出现在密码字段中,而出现在用户名字段中。这可能是什么原因?输入字段上缺少第一个字母

$("#username").keypress(function() 
{ 
    if($(this).hasClass("label")) 
    { 
    $(this).removeClass("label"); 
    $(this).val(""); 
    } 
}); 

$("#password").keypress(function() 
{ 
    if($(this).hasClass("label")) 
    { 
    $(this).removeClass("label"); 
    $(this).prop("type", "password"); 
    $(this).val(""); 
    } 
}); 

见这里的例子:https://jsfiddle.net/c0qdj1u3/

+2

对我来说很好Chrome ... Windows – DaniP

+0

这似乎是一个浏览器问题。 –

+0

在OS X上运行良好的Chrome –

回答

0

下面的行导致错误:

$(this).prop("type", "password"); 

如果你开始的类型为密码,它工作正常。而不是设置值,请使用占位符。请看下图:

<input type="text" placeholder="Username" class="label" id="username"><br> 
<input type="password" placeholder="Password" class="label" id="password"> 

$("#username").keypress(function() 
{ 
    if($(this).hasClass("label")) 
    { 
    $(this).removeClass("label"); 
    $(this).val(""); 
    } 
}); 

$("#password").keypress(function() 
{ 
    if($(this).hasClass("label")) 
    { 
    $(this).removeClass("label"); 
    $(this).val(""); 
    } 
}); 

如果你必须在任何打字之前的文本框中某个值,请尝试使用jQuery的占位符插件。 https://github.com/mathiasbynens/jquery-placeholder

+0

是的,我知道这条线是它造成的,但为什么?我不想使用占位符,因为IE9显然不支持它。你能提出一种解决方法吗? –

+0

您需要提前发布文字吗? –

+0

是的,因为它是输入字段标签。我也不想为这样简单的事情使用任何插件。 –

相关问题