2016-02-27 102 views
0

我試圖捕獲我的JQuery應用程序的所有關鍵事件。當使用​​事件時,我可以獲得輸入和選項卡事件,但所有字母均爲大寫。所以,我試圖切換到keypress,我聽說是較低的大寫字母。這工作,除了它不會捕獲進入和標籤事件了。有兩全其美嗎?我如何可以捕獲所有事件,區分大小寫包括像輸入鍵,Tab鍵,Shift,Alt等JQuery按鍵與keydown事件捕獲所有鍵碼

+0

'。 on('keypress,keydown'.....'可能是? – Gogol

+0

但是不會調用兩個事件?如何區分爲每個事件生成的代碼?例如,如果按下了一個字母鍵,我想要'keypress'事件中的字符代碼,如果它是非字母鍵,我需要'keydown'事件中的代碼。 –

+0

不可以在按鍵中捕捉輸入和製表符。 –

回答

0

在按鍵按下事件,與事件調用此方法作爲參數,並添加這一行,

e.preventDefault() 

這將暫停操作。

謝謝,

+0

這不回答我的問題。也許重讀它? –

+0

爲按鍵和按鍵事件調用此函數。 –

0

如何做到這一點?

$(window).on('keydown keypress', function(e) { 
    e.preventDefault(); 
    var code = e.keyCode || e.which; 
    console.log(code); 
}); 

什麼這在理論上應該做的是防止其他事件被解僱,而是因爲我們呼籲雙方的keydown和按鍵,其中一人肯定會被解僱。現在這可能會對代碼的其餘部分產生負面影響,所以請謹慎使用它。

+1

我決定做'.on('keydown keypress',函數(e){...}'然後在函數中檢查它是哪個事件,如果它是'keydown'事件, ,刪除,選項卡等,如果它是一個'keypress'事件,我處理字母。 –

+1

希望我提供一些見解... –

0

希望這有助於你正在嘗試做

$(document.body).on('keypress', function(e) { 
    var keycode = e.keyCode; 

    var valid = 
    (keycode > 47 && keycode < 58) || // number keys 
    keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns) 
    (keycode > 64 && keycode < 91) || // letter keys 
    (keycode > 95 && keycode < 112) || // numpad keys 
    (keycode > 185 && keycode < 193) || // ;=,-./` (in order) 
    (keycode > 218 && keycode < 223); // [\]' (in order) 
    if (valid) { 
    console.log(keycode + ' keypress'); //printable char on keypress 
    } 

}); 

$(document.body).on('keyup', function(e) { 
    var keycode = e.keyCode; 
    var valid = 
    (keycode > 47 && keycode < 58) || // number keys 
    keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns) 
    (keycode > 64 && keycode < 91) || // letter keys 
    (keycode > 95 && keycode < 112) || // numpad keys 
    (keycode > 185 && keycode < 193) || // ;=,-./` (in order) 
    (keycode > 218 && keycode < 223); // [\]' (in order) 
    if (!valid) { 
    console.log(keycode + ' keyup'); //non printable char on keyup 
    } 
}); 

有可見字符驗證從這個SO link

+0

我得到了一個工作解決方案,但感謝您的答案。 –

-1
$(".num").keypress(function (e) { 
    console.log('[keypress] key' + e.key + ' keyCode' + e.keyCode + ' which' + e.which); 
    var kc = e.keyCode || e.which; 
    if (kc < 48 || kc > 57)/* number keys*/ { 
     //$.alertme('no'); 
     if (e.preventDefault) { 
      e.preventDefault(); 
      console.log('[keypress] preventDefault'); 
     } else { 
      e.returnValue = false; 
      console.log('[keypress] returnValue'); 
     } 
    } 
    //$.alertme('ok'); 
    //var re = /[0-9]/.test(e.key);//not working android browser 
    //if (!re) { 
    // if (e.preventDefault) { 
    //  e.preventDefault(); 
    // } else { 
    //  e.returnValue = false; 
    // } 
    //} 
}); 

檢查僅數 添加NUM類輸入文字

+0

這不是他的問題的答案,他問的東西絕對不同。 – shaggy