2012-02-26 25 views
1

我有這樣的事情:如何設置多個動作中的jQuery

$('#find').click(function() {... 

我還需要添加到該事件,如果他們按ENTER鍵也將被執行。

我想沿着線的東西:

var code = (e.keyCode ? e.keyCode : e.which); 
if (($('#find').click()) || (code == 13)) { 

但很明顯,這是行不通的。我怎樣才能將兩種方式合併爲一個。只有在id =「code」的輸入中完成後,才能按Enter鍵。 click事件是用於id =「find」的另一個輸入類型按鈕。我想合併兩者,如果用戶在輸入代碼時按下Enter或單擊按鈕發送代碼,則兩種方式的工作方式都是相同的。

+0

只需設置'#find'爲'類型=「提交」',它會工作的全自動輸入。 – dfsq 2012-02-26 18:03:51

回答

4

,你可以做這樣的:

function myHandler(){ 
    $(this).css('background-color', 'green'); //whatever you need to do here 
} 
$('#find').click(myHandler); 
$('#find').keypress(function(){ 
    var code = (e.keyCode ? e.keyCode : e.which); 
    if(code == 13) myHandler(); 
); 

或可能使用KEYUP,你應該閱讀該文檔:http://api.jquery.com/keyup/

+1

+1正在寫類似 – Sarfraz 2012-02-26 17:54:37

+0

感謝mindandmedia。 – 2012-02-26 18:09:11

+0

歡迎你,哥們 – mindandmedia 2012-02-26 18:12:52

0

這個擴展名是:

$('#find').on('click',function(event,params) { 

    // your click code here  

}).on('keypress'),function(event) { 

    // if you have 13, then send the click evnet 
    // this way lets you do other things by passing the params 
    // object, if you wish 

    var code = (e.keyCode ? e.keyCode : e.which); 
    if(13 == code) { 
    $(this).trigger('click'); 
    return false; 
    } 

    // other code that executes if code != 13 

}); 
1

使用on()

$('#find').on('click keypress', function(e){ 
    if (e.type == 'click' || e.which == '13') { 
     // do stuff 
    } 
}); 

JS Fiddle demo

參考文獻:

+0

非常好的方式大衛。 – 2012-02-26 18:14:43

+0

很高興能有幫助。 =) – 2012-02-26 18:26:07

相關問題