[英]How to get a key press to correspond to the function that gets called first in javascript
所以我正在嘗試一些東西,如果你有兩個函數想要在按下相同的鍵后調用,如下所示:
var plus = function () {
document.addEventListener("keyup", function(e) {
if (/[+]/g.test(e.key)) {
console.log("plus");
}
})
}
plus();
var minus = function() {
document.addEventListener("keyup", function(e) {
if (/[-]/g.test(e.key)) {
console.log("minus");
}
});
}
minus();
function check() {
document.addEventListener("keyup", function(e) {
if(plus) {
if (e.keyCode == 13) {
console.log("enter pressed after plus");
plus = false;
minus = function() {
document.addEventListener("keyup", function(e) {
if (/[-]/g.test(e.key)) {
console.log("minus");
}
});
}
}
} else if(minus) {
if (e.keyCode == 13) {
console.log("enter pressed after minus");
minus = false;
plus = function () {
document.addEventListener("keyup", function(e) {
if (/[+]/g.test(e.key)) {
console.log("plus");
}
})
}
}
}
});
}
check();
如果你先按減號然后輸入console.log("enter pressed after plus")
press console.log("enter pressed after plus")
由於代碼的順序總是首先被調用,即使我想要做的是我希望輸入與我按下的鍵相對應首先,如果我先按加號,那么我希望console.log("enter pressed after plus")
press console.log("enter pressed after plus")
被調用,如果我先按減號,那么我希望console.log("enter pressed after minus")
press console.log("enter pressed after minus")
被調用。
任何幫助將不勝感激,並提前致謝。
哦,也很抱歉這個愚蠢的標題,想不出更好的了。
為了稍微清理一下(保持DRY ),您可以將所有事件處理程序邏輯移動到單個函數中並使用單個偵聽器。
為了跟蹤上次按下的鍵,我們可以使用在函數外部作用域中定義的變量。 並且,在每個事件之后更新它。 然后,當按下“Enter”時,我們可以檢查最后一個鍵是什么並相應地記錄。
此外, KeyboardEvent.keyCode
屬性已折舊。 您應該改用KeyboardEvent.code
屬性。
const input = document.querySelector('input') const log = document.getElementById('log') function check() { let lastKey = null input.addEventListener('keyup', ({ key }) => { if (['+', '-', 'Enter'].includes(key)) { // we only care about these keys if (key === '+') log.textContent = 'plus' if (key === '-') log.textContent = 'minus' if (key === 'Enter') { // `Enter` was keyed, what was keyed last? if (lastKey === '+') log.textContent = 'enter pressed after plus' if (lastKey === '-') log.textContent = 'enter pressed after minus' } lastKey = key // current key becomes last key } }) } check()
<input placeholder="Click here, then press and release a key." size="40"> <p id="log"></p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.