有一个按钮,当用户点击按钮时,一些数据被保存到后端.问题是当用户非常快速地点击按钮时,事件处理程序将被多次执行.
这是代码
var x = 1; $('#button').click(function() { // Do something // Save some data on network x++; console.log(x); });
我希望当用户单击按钮一次时执行此处理程序.即使在双击或三击的情况下,也只能执行一次.我只是想避免快速点击,这个处理程序可以再次执行
我心中有多种解决方案
定义一个全局变量IS_BUTTON_HANDLER_WORKING = false
,当你输入处理程序时将其设置为true,最后再将它设置为false.并检查是否真的只是从函数返回.
在开头分离处理程序并在最后重新附加.
假设您的应用程序中有25个按钮.应该是实现这一目标的最佳方法.
看看这个小提琴
解$('#button').click(function() { $(this).attr('disabled', true); // Do something // Save some data on network $(this).removeAttr('disabled'); });
使用这个,我们确信我们的下一个处理程序只有在完全执行上一次执行时才会执行.
大卫沃尔什有一个很好的解决方案.
// Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; };
有多种方法可以解决这个问题:
点击后你可以disable
/ hide
按钮:
$('#button').attr("disabled", true);
您还可以在每次单击时设置超时,以确保它不会再次执行:
var x, y = 1; $('#button').click(function() { if (x) clearTimeout(x); x = setTimeout(function() { // do the work here y++; console.log(y); // ---------------- }, 1000); });
因此,每次单击该按钮时,它只会在a之后实际执行代码1000 milliseconds
,如果快速连续单击该按钮,则超时将被清除并重新开始.
请注意,上述内容未经测试
就个人而言,我认为禁用的解决方案是最好的,因为它向用户表明他已经点击并且正在发生一些事情,你甚至可以在按钮旁边显示一个加载器.