我想按一下按键,会显示一个警告框。它完成了。但问题是我在页面内有一个文本框,当我尝试在文本框中输入时,警报框也会出现。
$(document).ready(function() {
$(document).keydown(function(e) {
if (e.key == "F8") {
alert('Right key pressed');
} else {
alert("Error key pressed")
}
e.preventDefault();
})
});
HTML:
<input type="text" />
答案 0 :(得分:2)
Textbox是您document
的元素,因此提升document
事件是一种很好的行为。
您应该将文本框中的处理程序添加到stop propagate事件到document
图层
$('input').keydown(function (e) {
e.stopPropagation();
}
答案 1 :(得分:0)
尝试使用事件侦听器:
$(document).ready(function() {
var keyListner = function (e) {
e.preventDefault();
if (e.key == 'F8') {
console.log('Right key pressed');
} else {
console.log('Error key pressed')
};
}
// Set the event listener
$(document).on('keyup', 'body', keyListner);
// Disable it on focus
$('input, textarea').focus(function() {
$(document).off('keyup', 'body', keyListner);
});
// Enable it on blur
$('input, textarea').blur(function() {
$(document).on('keyup', 'body', keyListner);
});
});