JQuery: keydown () only runs once

What I'm trying to do is that I press w and it gives a warning with the message "first Alert", after which I want to press w again and it will display a "second alert".

So, what I did here, I created a variable called "a", which I set to 0, then I have 2 functions called firstAlert, and the second - secondAlert, which add 1 to "a".

I created an if statement to check if user w clicked. Inside the if statement, I created a switch statement that checks the value of โ€œaโ€ and runs a specific case, depending on what value the value of โ€œaโ€ has.

My problem is that when I first press w, it runs the firstAlert () function and prints "first Alert". But the second time, when I press w, the second function does not start at all, and in some browsers the first function works when I press w.

the code:

$(document).ready(function() {

    var a = 0;

    function firstAlert() {
      alert("first Alert");
      a + 1;
    }

    function secondAlert() {
      alert("second Alert");
      a + 1;
    }

    $(document).keydown(function(key) {
      if (key.which == 87) {
        switch (a) {
          case 0:
            firstAlert();
          break;

          case 1:
            secondAlert();
          break;

          default:
            a = 0;
          break;
      }
    }
  });
 });
+4
source share
4 answers

Looks like you want to enlarge. Try (Equivalently ) a+=1; a=a+1;

+2
source

Without fixing your other code, it a++will provide you with what you are looking for:

jQuery(document).ready(function($) {

  var a = 0;

  function firstAlert() {
    alert("first Alert");
    a++;
  }

  function secondAlert() {
    alert("second Alert");
    a++;
  }

  $(document).keydown(function(key) {
    if (key.which == 87) {
      switch (a) {
        case 0:
          firstAlert();
          break;

        case 1:
          secondAlert();
          break;

        default:
          a = 0;
          break;
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run codeHide result
+2
source

, jQuery ( > 3), -, keydown :

$(document).on('keydown', 'document', function (){
     //Your code here
});
0

$(document).ready(function() {

    var a = 0;

    function firstAlert() {
      alert("first Alert");
      a+=1;
    }

    function secondAlert() {
      alert("second Alert");
      a+=1;
    }

    $(document).keydown(function(key) {
      if (key.which == 87) {
        switch (a) {
          case 0:
            firstAlert();
          break;

          case 1:
            secondAlert();
          break;

          default:
            a = 0;
          break;
      }
    }
  });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hide result
0

Source: https://habr.com/ru/post/1675973/


All Articles