JavaScript 按 Enter 键两次,每次按键后执行不同的操作

JavaScript Press Enter Key Twice With Different Actions After Each Keypress

我需要帮助在纯 JS 中按两次 Enter 键并在每次按键后发生不同的操作(没有 jQuery),例如:

我可以执行第一个操作,但不能执行第二个操作。这是我的代码:

var enterPressed = 0;
window.onkeydown = function (e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 
    if (enterPressed === 0) {
      enterPressed = 1;
      e.preventDefault(); 
      console.log("Enter pressed once. enterPressed is " + enterPressed);
    } else if (enterPressed === 1) {
      e.preventDefault(); 
      console.log("Enter pressed twice. enterPressed is " + enterPressed);
    }
   }
 };

Here's a Plunk.

知道我做错了什么吗?谢谢

当您在 "document" 上书写时,您将丢弃所有 JS 代码。

您需要将该答案放在另一个元素上,例如 a , document.getElementById('result'),然后将结果写入该元素。

Here is your plunk good sir

var enterPressed = 0;
window.onkeypress = function (e) {
 var keyCode = (e.keyCode || e.which);
 if (keyCode === 13) {
  alert('key');
  if (enterPressed === 0) {
   enterPressed++;
   document.getElementById("result").innerHTML = "Enter pressed once. enterPressed is " + enterPressed;
  } else if (enterPressed === 1) {
   e.preventDefault(); 
   document.getElementById("result").innerHTML = "Enter pressed twice. enterPressed is " + enterPressed;
  }
 return;
 }
};