【问题标题】:How can I make an output to print +1 every time I do an onkeydown Event in javascript?每次在javascript中执行onkeydown事件时,如何输出打印+1?
【发布时间】:2021-06-27 04:40:25
【问题描述】:

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

html 中的输出是:

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

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

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

等等

【问题讨论】:

  • document.getElementById("moreNum").addEventListener("keydown", myFunction); 之后你可以按照你想要的方式定义函数function myFunction() { //increase your counter }
  • 我试过这个:让 outputElement = document.getElementById("moreNum"); outputElement.innerHTML = '你按了多少次"m": ' += 1 ;

标签: javascript events onkeydown


【解决方案1】:

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

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);
&lt;h1 id="moreNum"&gt;how many times have you pressed the "m": 0&lt;/h1&gt;

【讨论】:

    【解决方案2】:

    这应该工作:)

    <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
        
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 2021-06-21
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 2015-10-27
      • 2016-10-19
      相关资源
      最近更新 更多