javascript 使用延迟触发方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8711314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use trigger method with delay
提问by Gildas Ross
I would use the trigger method with a delay before the execution, I try this way:
我会在执行前延迟使用 trigger 方法,我尝试这种方式:
$('#open-contact').delay(3000).trigger('click');
but the code runs instantly.
但代码立即运行。
Do any of you could help me?
你们中有人可以帮助我吗?
thank you very much
非常感谢你
回答by Sergio Tulentsev
jQuery doc says:
jQuery文档说:
The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.
.delay() 方法最适合在排队的 jQuery 效果之间延迟。因为它是有限的——例如,它没有提供取消延迟的方法——.delay() 不是 JavaScript 原生 setTimeout 函数的替代品,它可能更适合某些用例。
So, I would rewrite this as
所以,我会把它改写为
setTimeout(function() {
$('#open-contact').trigger('click');
}, 3000);
回答by lfxgroove
From jQuerys documentation about delay:
来自关于延迟的 jQuery 文档:
The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.
.delay() 方法最适合在排队的 jQuery 效果之间延迟。因为它是有限的——例如,它没有提供取消延迟的方法——.delay() 不是 JavaScript 原生 setTimeout 函数的替代品,它可能更适合某些用例。
In other words you should use setTimeout() instead, ie:
换句话说,您应该使用 setTimeout() 代替,即:
setTimeout(function () { $('#open-contact').trigger('click'); }, 3000);
回答by Sudhir Bastakoti
Try:
尝试:
$('#open-contact').delay(3000).queue(function() {
$(this).trigger('click');
});