每次我在 javascript 中执行 onkeydown 事件时,如何使输出打印 +1?

How can I make an output to print +1 every time I do an onkeydown Event in javascript?

我需要做一个 onkeydown 事件,当我按下 m 键时,它会在输出中打印一个 +1

html 中的输出是:

<h1 id="moreNum">how many times have you pressed the "m": 0</h1>

当我输入 m 时,它会打印出:你按了多少次“m”:1

如果我再次点击它,它会打印:你按了多少次“m”:2

等等

您可以 addEventLisetner 并仅在按下的键是 m 时使用 event 对象提供的 key 增加计数。

const h1 = document.querySelector("#moreNum");
let count = 0;

function setText(times) {
  h1.textContent = `how many times have you pressed the "m": ${times}`
}

function logKey(e) {
  if (e.key === 'm') {
    ++count;
    setText(count);
  }

}

document.addEventListener('keydown', logKey);
<h1 id="moreNum">how many times have you pressed the "m": 0</h1>

这应该有效:)

<h1 id="moreNum">how many times have you pressed the "m": <span id="counter"></span></h1>


let count = 0;
document.addEventListener('keydown', logKey);

function logKey(e) {
  if (e.which === 77) {
    count = count + 1
    document.getElementById('counter').innerHTML = count
    
  }
}