首页 > 解决方案 > 如何在按下和按下按钮时连续递增

问题描述

您能否看一下这个片段,让我知道如何在单击并按下 inindex时连续增加?#adder

var index = 0;
$("#adder").on("click", function(){
  ++index;
   $("#res").html(index);
});

$("#adder").on("keydown", function(){
  ++index;
   $("#res").html(index);
});

$("#adder").on("keypress", function(){
  ++index;
   $("#res").html(index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <button type="button" class="btn btn-default" id="adder">+</button>
 <div id="res"> </div>

标签: javascriptjquery

解决方案


这是一个使用mousedownmouseup事件处理程序的示例,并使用setInterval不断添加索引。

已编辑

恢复了单击后立即增加索引的单击事件处理程序。

已编辑

添加限制条件

var index = 0;
var interval;
var timeout;

// $("#adder").on("click", function(){
//  increase();
// });

$("#adder").on("mousedown", function(){
  increase();
  timeout = setTimeout(function(){
    interval = setInterval(function(){
      increase();
    }, 100);
  }, 500);
});

$("#adder").on("mouseup", function(){
  clearTimeout(timeout);
  clearInterval(interval);
});

function increase(){
    $("#res").html(++index);
    checkLimit();
}

function checkLimit(){
                   
    // here to check stop increasment
    if(index >= 50 ){
      // stop interval
      clearInterval(interval);
      // remove event handler
      $("#adder").off('click').off('mousedown').off('mouseup');
      return;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <button type="button" class="btn btn-default" id="adder">+</button>
 <div id="res"> </div>


推荐阅读