jQuery - 检测输入是否在X秒内按下X次以上

时间:2016-12-02 12:04:45

标签: jquery

我收到了一个AJAX聊天,这是发送消息的代码:

$('#usermsg').keydown(function(e) {
    var key = e.which;
    if(key == 13)  // the enter key code
    {
        var clientmsg = $("#usermsg").html();
        if((jQuery.trim(clientmsg)).length==0)
        {
            return false;
        }

        $.ajax({
             // .............
        });
    }
});

我想在$('#usermsg')

时检测是否有人在2秒内按下了3次以上的次数

最简单,最好的方法是什么?

2 个答案:

答案 0 :(得分:4)

var enterCounter = 0;

$('#usermsg').keydown(function(e) {
    var key = e.which;
    if(key == 13) { // the enter key code        

        if (++enterCounter > 3) alert('pressed enter more than 3 times in 2 seconds');
        setTimeout(function(){enterCounter--;}, 2000);

        var clientmsg = $("#usermsg").html();
        if((jQuery.trim(clientmsg)).length==0) {            
            return false;
        }

        $.ajax({
             // .............
        });
    }
});

答案 1 :(得分:0)



var countTime=0;
$('#usermsg').on('keydown', function(e){
  var key = e.which;
  if(key == 13) {  // the enter key code
    if (countTime==0){
      countTime++;
      setTimeout(function(){countTime=0},2000)
      var clientmsg = $("#usermsg").html();
      if((jQuery.trim(clientmsg)).length==0) {
        return false;
      }
      $.ajax({
        // .............
      });
    } else {
      countTime++;
      if (countTime>=3) countTime=0;
    }
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="usermsg"/>
&#13;
&#13;
&#13;