2017-02-20 36 views
1

我在我的應用程序的不同頁面上有表單。按「Enter」或「Esc」後,當前頁面上的表格必須是「已提交」或「已取消」。 keydown()函數應該在頁面的任何位置觸發,而不是綁定到特定的DOM元素。只爲當前頁面捕獲keyDown

的.js

$(document).keydown(function(e) { 
     if(e.which == 13) { 
      // enter pressed 
      $('#submitCreateAccountForm').click(); 
      $('#submitForm').click(); 
      $('#submitNewSubmissionForm').click(); 
     } 
     if(e.which == 27) { 
      // esc pressed 

      $('#submitCreateAccountFormCancel').click(); 
      $('#submitFormCancel').click(); 
      $('#submitNewSubmissionFormCancel').click(); 
     } 
    }); 

我應該 '文件' 被替換?由於

回答

1

試試這個

$(function(){ 

    $('html').bind('keypress', function (e) { 
     if (e.keyCode == 13) { 
     //do somethings 
     } 
     else if (e.keyCode == 27) { 
     return false; 
     } 
    }); 
}); 
+0

這仍然在所有頁面調用按鍵功能,而不僅僅是當前活動的頁面。 – dmat

0

你可以試試這個代碼:

$("body").keyup(function(event){ // bind keyup event to body 
    if(event.keyCode == 13){  // 13 - code of enter key (find for ESC) 
     $("#enter").click();  // bind enter press for clicking botton with id="enter" and corresponding actions 
    } 
});