当我拿出我的计算器时,我希望能够根据我的选择使用键盘或鼠标。我以为我已经为键盘编码了。当它发生这种情况时,键盘按键不会向控制台打印任何内容,除非我首先点击屏幕上的相应按钮(即,给它焦点)。然后,我可以将任何键混合并仅按照我的意愿打印焦点数。如果我想更改数字,我必须给出所需的数字焦点,然后键盘上的相应数字将打印到控制台。
如何调整代码,以便在加载DOM后,键盘自动工作,无需关注按钮?
$(document).ready(function () {
// declare empty infix string
let infix = "";
// get input from user on key press (separate function)
$(function getInput() {
$('#one').on("keyup", function() {
infix += "1";
console.log(infix);
});
$('#two').on("keyup", function() {
infix += "2";
console.log(infix);
});
$('#three').on("keyup", function() {
infix += "3";
console.log(infix);
});
$('#four').on("keyup", function() {
infix += "4";
console.log(infix);
});
$('#five').on("keyup", function() {
infix += "5";
console.log(infix);
});
$('#six').on("keyup", function() {
infix += "6";
console.log(infix);
});
$('#seven').on("keyup", function() {
infix += "7";
console.log(infix);
});
$('#eight').on("keyup", function() {
infix += "8";
console.log(infix);
});
$('#nine').on("keyup", function() {
infix += "9";
console.log(infix);
});
$('#zero').on("keyup", function() {
infix += "0";
console.log(infix);
});
}());
});
答案 0 :(得分:1)
事实上,关键事件传播到窗口应该会大大简化您的问题。
通过简单的白名单检查替换听众疯狂。
// $(fn) is equivalent to $(document).ready(fn)
$(function() {
// declare empty infix string
let infix = "";
// get input from user on key press (separate function)
(function getInput() {
$(window).on('keyup', function(e) {
if("1234567890".includes(e.key)) {
infix += e.key;
console.log(infix);
}
});
})(); // It's IIFE, not jQuery
});