Javascript 如何使用delay()清除事件调用集
我有两个按钮,批准(可见)和撤消(不可见)。单击“批准”隐藏按钮并显示“撤消”按钮(表示为故障保护)。单击“批准”设置20秒延迟,如果实现,将提交表单。但是,我希望“取消批准”按钮取消延迟。在不完全删除窗体上的事件处理程序的情况下,如何最好地执行此操作Javascript 如何使用delay()清除事件调用集,javascript,jquery,Javascript,Jquery,我有两个按钮,批准(可见)和撤消(不可见)。单击“批准”隐藏按钮并显示“撤消”按钮(表示为故障保护)。单击“批准”设置20秒延迟,如果实现,将提交表单。但是,我希望“取消批准”按钮取消延迟。在不完全删除窗体上的事件处理程序的情况下,如何最好地执行此操作 $("button.approve").on('click', function(e){ $(this).hide(); $(this).siblings('button.undo').show()
$("button.approve").on('click', function(e){
$(this).hide();
$(this).siblings('button.undo').show();
$(this).siblings("form.update-comment.approve").delay(20000).trigger('submit');
});
$("button.undo").on('click', function(e){
$(this).hide();
$(this).siblings('button.approve').show();
$(this).siblings("form.update-comment.approve").off('submit');
});
你看到桌子上的黄色盒子了吗
.delay()
方法最适合在排队的jQuery效果之间进行延迟。因为它是有限的-例如,它没有提供取消延迟的方法。。delay()
不是JavaScript本机setTimeout函数的替代品,后者可能更适合某些用例
使用设置超时
var approveTimeout;
$("button.approve").on('click', function(e){
var self = $(this);
self.hide().siblings('button.undo').show();
approveTimeout = setTimeout(function(){
self.siblings("form.update-comment.approve").trigger('submit');
}, 20000);
});
$("button.undo").on('click', function(e){
$(this).hide().siblings('button.approve').show();
clearTimeout( approveTimeout );
});
您可以使用
setTimeout
和clearTimeout
执行此操作:
function onSubmit(form) {
form.submit();
};
var delayedSubmit = null;
$("button.approve").on('click', function(e){
$(this).hide();
$(this).siblings('button.undo').show();
var thisForm = $(this).siblings("form.update-comment.approve");
delayedSubmit = setTimeout(function() {
onSubmit( thisForm );
}, 2000);
});
$("button.undo").on('click', function(e){
$(this).hide();
$(this).siblings('button.approve').show();
clearTimeout( delayedSubmit );
});
试一试
看,
var form=$(“form.update comment.approve”)
,approve=$(“button.approve”)
,undo=$(“button.undo”);
关于职能(e)的“提交.批准”表格{
e、 预防默认值();
e、 停止传播();
警报(例如名称空间);
撤销触发器(“单击“,[“重置”])
});
批准。点击功能(e){
批准。隐藏();
undo.show();
形式
.延迟(20000,“批准”)
.队列(“批准”,功能(){
表.触发器(“提交.批准”);
}).退出(“批准”);
});
在('click',函数(e,reset)上撤消.hide(){
形式
//清除队列
.队列(“批准”、[]);
undo.hide();
approve.show();
控制台日志(重置| |“取消”);
});代码>
批准
撤消
可能的重复:延迟
用于效果和动画,而不是触发器
功能。感谢您的帮助。我忘了添加页面上有多个表单,所以我使用了您的代码并添加了一个对象来跟踪要取消的setTimeout[code}var container={};var forms=$(“.update comment.approve”);forms.each(函数(索引){container['timeout'+index]=0;});[/code]
var form = $("form.update-comment.approve")
, approve = $("button.approve")
, undo = $("button.undo");
form.on("submit.approved", function (e) {
// do stuff
undo.trigger("click", ["reset"])
});
approve.on('click', function (e) {
approve.hide();
undo.show();
form
.delay(20000, "approval")
.queue("approval", function () {
form.trigger('submit.approved');
}).dequeue("approval");
});
undo.hide().on('click', function (e, reset) {
form
.queue("approval", []);
undo.hide();
approve.show();
console.log(reset || "cancelled");
});