gpt4 book ai didi

javascript - 当用户停止点击时触发事件

转载 作者:行者123 更新时间:2023-11-28 19:40:45 25 4
gpt4 key购买 nike

我能够使用 jQuery 检测按钮的点击

$('#myButton').click(function(){
// do something
});

但是,当用户多次单击该按钮时,它会触发不必要的中间事件。

我想仅在最后一次单击按钮时触发事件。

类似于:

$('#myButton').lastClickOnASequenceOfClicks(function(){
// ignore the multiple clicks followed
// do something only on the last click of a sequence of clicks
});

这样,如果用户点击 10 次(有一点时间间隔),它应该仅在第十次点击时触发事件。

最佳答案

每次点击都会重置计时器。

var timer;

$("#myButton").click(function () {
var timeToWait = 1000;
clearTimeout(timer);
timer = setTimeout(function () {
// do something only on the last click
}, timeToWait);
}

更新

解决用户生成的“多次点击事件”问题的另一种方法是执行OP评论部分中提到的操作。第一次点击时执行某些操作,然后禁用按钮,以便用户无法再单击它(也可以设置按钮再次启用的时间)

var timer, timeToWait = 5000, selector ="#myButton";

$(selector).click(function (e) {
$(this).attr("disabled", "disabled");
// do something
// Then wait a certain amount of time then remove the disabled attr on your button
timer = setTimeout(function () {
$(selector).removeAttr("disabled");
}, timeToWait);
})

关于javascript - 当用户停止点击时触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25089727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com