我在 4 种情况下使用 4 种方法,请先在这里使用我的 awnser:Prevent double submits in a Rails AJAX form
用户只点击限制:
使用 stopImmediatePropagation 并向目标 dom 添加一个点击事件。
/**
* 防止按钮重复点击。
* NOTICE: #1 需要在作用点之前调用此方法 #2 stopImmediatePropagation 会阻止后面的所有事件包括事件冒泡
* @delay_duration 两次点击的间隔时间
*/
$.fn.preventMultipleClick = function (delay_duration) {
delay_duration = delay_duration || 3000;
var last_click_time_stamp = 0;
var time_duration = 0;
$(this).bind('click', function (event) {
time_duration = last_click_time_stamp ? event.timeStamp - last_click_time_stamp : 0;
//console.debug("preventMultipleClick", last_click_time_stamp, time_duration);
if (time_duration && time_duration < delay_duration) {
event.stopImmediatePropagation();
} else {
//console.debug("skip preventMultipleClick~");
last_click_time_stamp = event.timeStamp;
}
});
};
限制提交如ajax:
使用 ajax 的 beforeSend 属性。
/**
* 使用:
* 在jquery的ajax方法中加入参数:beforeSend
* 例如:beforeSend: function(){return $.preventMultipleAjax(event, 5000)}
*
* @param event
* @param delay_duration
* @returns {boolean}
*/
$.preventMultipleAjax = function (event, delay_duration) {
delay_duration = delay_duration || 3000;
var target = $(event.target);
var last_click_time_stamp = target.attr("_ajax_send_time_stamp") || 0;
var time_duration = last_click_time_stamp ? event.timeStamp - last_click_time_stamp : 0;
//console.debug("preventMultipleAjax", last_click_time_stamp, time_duration);
if (time_duration && time_duration < delay_duration) {
return false;
} else {
//console.debug("skip preventMultipleAjax~");
target.attr("_ajax_send_time_stamp", event.timeStamp);
return true;
}
};
仅适用于形式:
<%= f.submit "Save annotation", :disable_with => "Saving...", :class => "btn btn-primary", :id => "annotation-submit-button" %>
或者:禁用:对表单元素,按钮等,会阻止上的事件触发
<input type="submit" value="submit" />
<input type="button" value="button" />
<input type="image" value="image" />
其他:
这是宝石:<a href="https://github.com/mlanett/redis-lock" rel="nofollow noreferrer">https://github.com/mlanett/redis-lock
Redis.current.lock("#{current_user.id}.action_name") do
# Some code
end