2012-09-04 85 views
2

我有一個驗證表單。 當PHP發現錯誤,將輸入與「錯誤」類...例如:專注於第一個類名元素

<input type='text' name='login' class='error'/> 
<input type='password' name='pass'/> 
<input type='text' name='email' class='error'/> 

我的問題是,如何設置焦點在使用jQuery第一個「錯誤」類別的元素?如果我試試這個:

<script type='text/javascript'> 
    if($(".error").length != 0){$(".error").focus();} 
</script> 

總是將焦點設置在最後一個元素上。 感謝您的幫助。

+0

[如何獲得第n個元素的jQuery(HTTP的可能重複:// stackoverflow.com/questions/1442925/how-to-get-nth-jquery-element) –

回答

11

您可以使用:first選擇器。

$("input.error:first").focus() 
+0

感謝兄弟由你決定 –

+0

@StefanLuv不客氣。 – undefined