2012-03-12 91 views
0

我有一個窗體上的jQueryUI按鈕(不是模態對話框)。我想在用戶點擊Enter鍵時觸發它。我怎樣才能做到這一點?這裏是我的代碼:jQueryUI按鈕上的默認按鈕上按Enter鍵

HTML:

<a href="javascript:void(0);" id="loginButtonInner">Login</a> 

JS:

$(document).ready(function() 
{ 
    $("#loginButtonInner").button(getButtonOptions("ui-icon-unlocked", true)); 
    $("#loginButtonInner").button("option", "disabled", true); 
    $("#loginButtonInner").unbind("click"); 
} 

.... 

if (userNameValid && passwordValid) 
    {  
     $("#loginButtonInner").button("option", "disabled", false); 
     $("#loginButtonInner").unbind("click").bind("click", function() { authenticateUser(); return false; }); 
    } 
    else 
    {  
     $("#loginButtonInner").button("option", "disabled", true); 
     $("#loginButtonInner").unbind("click"); 
    } 

目前,我必須標籤通過鍵盤來達到按鈕或通過鼠標點擊。

我在網上搜索解決方案,但他們都指向一個模式對話框窗體按鈕。

謝謝!

回答

2

添加一鍵收聽到你的表單元素並觀察回車鍵,然後從你的按鈕觸發點擊:

$(yourform).find('*').keypress(function(e) { 
    if (e.which == 13) { // 13 is the code for Enter key 
     e.preventDefault(); 
     $(yourbutton).click(); 
    } 
}); 
+0

謝謝你們!我會嘗試這兩個選項!非常感激。 :) – user1100221 2012-03-12 02:47:58

1

您應該可以使用jQuery.focus()函數。 例如:

$("#loginButtonInner").focus(); 

將導致元件與loginButtonInner的ID來接收焦點。所以當你按下回車鍵時,如果這個元素是一個按鈕,它將被按下。

更新:我試着用jQueryUI按鈕,它工作正常。