javascript JQuery .click() 处理程序不能在函数周围接受 setTimeout()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18968585/
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
JQuery .click() handler can't accept setTimeout() around the function
提问by Dean Schulze
I want to program a delay in the .click(function() {...}) handler before the function is executed. This doesn't work:
我想在执行函数之前在 .click(function() {...}) 处理程序中编程延迟。这不起作用:
$('.okButton').click(setTimeout(function() { ...}, 3000))
It gives this error (in Chrome):
它给出了这个错误(在 Chrome 中):
Uncaught TypeError: Object 2 has no method 'apply'
The JQuery docs don't give any clue as to why this doesn't work.
JQuery 文档没有给出任何关于为什么这不起作用的线索。
How can I put a delay before executing the function handler?
如何在执行函数处理程序之前延迟?
采纳答案by Dean Schulze
The solution is to have a .click() handler function that just calls setTimeout() with a handle to the real handler function:
解决方案是有一个 .click() 处理函数,它只调用 setTimeout() 并带有真正的处理函数的句柄:
$('.okButton').click(function() {
setTimeout(okButtonClickHandler, 3000)
});
When I tried this before it called the handler function immediately because I include parenthesis on the argument to setTimeout().
当我在它立即调用处理程序函数之前尝试这个时,因为我在 setTimeout() 的参数上包含了括号。
Don't do this:
不要这样做:
$('.okButton').click(function() {
setTimeout(okButtonClickHandler(), 3000)
});
It will execute the handler function immediately.
它将立即执行处理程序函数。
回答by Pointy
It doesn't work because setTimeout()
doesn't return a function; it returns a timer handle (a number).
它不起作用,因为setTimeout()
不返回函数;它返回一个计时器句柄(一个数字)。
This should work:
这应该有效:
$('.okButton').click(function() { setTimeout(function() { ...}, 3000); });
The argument expressions in JavaScript function calls are always fully evaluated beforethe function is called. Your code called setTimeout()
, and the return value from that was passed into the jQuery routine.
JavaScript 函数调用中的参数表达式总是在调用函数之前完全计算。您的代码调用了setTimeout()
,其返回值被传递到 jQuery 例程中。
回答by FunkyMonk91
Why don't you put the timeout inside the callback?
你为什么不把超时放在回调中?
$('.okButton').click(function() {
setTimeout(function(){
alert("Hello");
},3000);
});
回答by Mika Tuupola
You can do something like:
您可以执行以下操作:
$(".okbutton").click(function(event) {
var timeout = setTimeout(function() {
alert("Foo");
}, 3000)
});
You can try out the working example. After clicking the word click it takes three seconds for the alert to appear.
您可以尝试工作示例。单击“单击”一词后,警报需要三秒钟才能出现。