iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 29
0
Modern Web

從Stack Overflow學前端系列 第 29

從StackOverflow上學CODING(29) 如何監聽判斷enter鍵?

How to detect pressing Enter on keyboard using jQuery?

I would like to detect whether the user has pressed Enter using jQuery.
How is this possible? Does it require a plugin?
EDIT: It looks like I need to use the keypress() method.
I wanted to know if anyone knows if there are browser issues with that command - like are there any browser compatibility issues I should know about?

我想要用jQuery偵測使用者有沒有按下enter鍵
這有可能嗎還是說我需要其他的插件
感覺上我好像需要keypress()這個方法
我想知道有沒有其他人知道這個方式有沒有可能造成瀏覽器錯誤,像是瀏覽器鄉容器錯誤之類的


The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:

jQuery最大的重點就是讓你不需要擔心瀏覽器相容性問題,我還滿確定你可以直接很安全的在所有瀏覽器中用"13"代表enter鍵,像這樣:

$(document).on('keypress',function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

上一篇
從StackOverflow上學CODING(28) 判斷兩個陣列中的不同點
下一篇
從StackOverflow上學CODING(30)用 jQuery預載圖片
系列文
從Stack Overflow學前端30

尚未有邦友留言

立即登入留言