文件層級綁定(全域熱鍵)
$(function() {
$(document).on("keydown", function(e) {
if (e.which === 13) { // Enter
// 執行動作
console.log("Enter pressed");
}
});
});
特定輸入框綁定
$("#searchInput").on("keydown", function(e) {
if (e.which === 13) {
e.preventDefault(); // 防止表單提交
doSearch();
}
});
原文代碼分析
$(function () {
document.onkeydown = function (event) {
var e = event || window.event || arguments.callee.caller.arguments[0];
if (e && e.keyCode == 13) {
// to do something
}
};
});
- 使用原生
document.onkeydown 而非 jQuery 事件
arguments.callee.caller.arguments[0] 為舊 IE 相容寫法(嚴格模式下失效)
- 建議統一使用
e.which(jQuery 正規化)
最佳實踐
// 表單內輸入框:Enter 提交
$("form").on("keydown", "input[type=text]", function(e) {
if (e.which === 13) {
$(this).closest("form").trigger("submit");
}
});
// 避免 textarea 觸發
$("form").on("keydown", "input:not([type=textarea])", function(e) {
if (e.which === 13) e.preventDefault(), $(this).blur(); // 讓表單 submit 事件處理
});