我有一些輸入與浮動標籤的頂部。其效果基本上是在電子郵件文本輸入框中輸入「輸入您的電子郵件」。當你點擊輸入時,標籤消失。我怎麼能這個jQuery功能好一點?
我對它有一個工作函數,但我有一些重複代碼。
IE:
我的HTML看起來像這樣:
<div id="action">
<form action="/" method="post" id="#register_form">
<input type="hidden" name="create" value="1" />
<div class="form-field">
<label for="register_name">Name (First & Last)</label>
<input id="register_name" class="form-text" type="text" name="name" tabindex="1"/>
</div>
<div class="form-field">
<label for="register_email">Enter your email</label>
<input id="register_email" class="form-text" type="text" name="email" tabindex="2"/>
</div>
<div class="form-field">
<label for="register_password">Password</label>
<input id="register_password" class="form-password" type="password" name="password" tabindex="3"/>
</div>
<button type="submit">Almost there!</button>
</form>
</div>
而jQuery的看起來像這樣:
$('#action input[type=text], #action input[type=password]').focus(function(){
// get this label
var this_id = $(this).attr('id');
$('label[for='+this_id+']').addClass('in_lighter');
}).blur(function(){
// get this label
var this_id = $(this).attr('id');
if($(this).val()==""){
$('label[for='+this_id+']').removeClass('in_lighter');
}
}).keyup(function(){
// get this label
var this_id = $(this).attr('id');
$('label[for='+this_id+']').fadeOut();
});
正如你可以看到,該函數取決於幾個不同的事情無論是焦點,模糊還是關鍵。然而,在這些功能中的每一箇中,它都會抓取所選輸入的id,然後使用它來標識要使用的標籤。正如你所看到的,我重複這個代碼3次:
// get this label
var this_id = $(this).attr('id');
有沒有更好的方法呢?更簡化的方法來實現相同的結果?
可能屬於codereview.se – zzzzBov 2011-03-05 01:22:07