简体   繁体   中英

Perform action depending on amount of times a key is pressed?

The keypress function below calls a certain function depending on how many times a given key is pressed. On execution, only the first if statement runs, and the second one does not.

$(document).keypress(function(number) {
      var pressCount = 0;
      pressCount++;

      if (number.which == 67 || number.which == 99) {
        if (pressCount = 1) {
          callThisFunction();
        } else if (pressCount = 2) {
          callThisOtherFunction();
          }
      }
 });

Its perhaps happening because "pressCount" is reset to 0 every time the function runs.

try the following tweak:

    var pressCount = 0;

$(document).keypress(function(number) {
      pressCount++;

      if (number.which == 67 || number.which == 99) {
        if (pressCount == 1) {
          callThisFunction();
        } else if (pressCount == 2) {
          callThisOtherFunction();
          }
      }
 });

You are missing an = sign inside your if statement. Change to:

if (pressCount == 1) {
    callThisFunction();
} else if (pressCount == 2) {
    callThisOtherFunction();
}

Also declare you pressCount variable outside of your function. Otherwise it will be reset to 0 everytime you press a key.

var pressCount = 0;

$(document).keypress(function(number) {
   ... // rest of your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM