【问题标题】:Perform action depending on amount of times a key is pressed?根据按键的次数执行操作?
【发布时间】:2017-10-29 19:01:44
【问题描述】:

下面的 keypress 函数根据给定键被按下的次数调用某个函数。执行时,只有第一个 if 语句运行,第二个不运行。

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

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

【问题讨论】:

    标签: javascript


    【解决方案1】:

    这可能是因为每次函数运行时“pressCount”都会重置为 0。

    尝试以下调整:

        var pressCount = 0;
    
    $(document).keypress(function(number) {
          pressCount++;
    
          if (number.which == 67 || number.which == 99) {
            if (pressCount == 1) {
              callThisFunction();
            } else if (pressCount == 2) {
              callThisOtherFunction();
              }
          }
     });
    

    【讨论】:

      【解决方案2】:

      您的if 语句中缺少= 符号。改为:

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

      还要在函数之外声明 pressCount 变量。否则每按一次键都会重置为0。

      var pressCount = 0;
      
      $(document).keypress(function(number) {
         ... // rest of your code
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-07
        • 2011-03-30
        • 2018-05-30
        • 1970-01-01
        相关资源
        最近更新 更多