javascript - 如何在按下和按下按钮时连续递增
问题描述
您能否看一下这个片段,让我知道如何在单击并按下 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>
解决方案
这是一个使用mousedown
和mouseup
事件处理程序的示例,并使用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>
推荐阅读
- java - 在 java 中创建一个带有 2 个键的索引和键的映射
- c++ - 使用优先级队列的 K 排序数组 - C++
- java - 无法从 Java 类获取自定义注解
- java - 从外部 URL 获取 thymeleaf 片段
- android - 将环境设置为 ExternalStorageDirectory 时,无法在 android 上使用 java 创建目录文件
- python - 直接从 Flask 服务上传到 Minio
- java - RestAssured - 如何从 json 响应中读取数组元素
- mysql - FDQuery和OnCalcFields,获取上一行
- java - 如何检查哪个线程当前正在锁定静态变量
- python-2.7 - 目录和文件的 Python 递归到 5 个级别