匿名函数内部的 setTimeout
我想在 jQuery 函数中调用 editObject() ,初始化调用确实有效,但 setTimeout 不起作用,如何让它运行?控制台说 setTimeout 调用时未定义 editObject:
(function($){
$.fn.extend({
...
editObject()
function editObject() {
alert("Test!");
setTimeout('editObject()', 1000);
}
return this.each(function() {
var o = options;
});
}
});
})(jQuery);
感谢帮助!
I want to call editObject() inside of my jQuery function, the initalisation call does work, but setTimeout doesn't work, how to get it running? Console says that editObject is not defined when called by setTimeout:
(function($){
$.fn.extend({
...
editObject()
function editObject() {
alert("Test!");
setTimeout('editObject()', 1000);
}
return this.each(function() {
var o = options;
});
}
});
})(jQuery);
Thanks for help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它不起作用,因为 editObject() 是在匿名函数的范围内声明的,但 setTimeout() 会评估您在全局上下文中传递给它的字符串。试试这个:
It doesn't work because editObject() is declared in the scope of your anonymous function, but setTimeout() evals the string you passed it in a global context. Try this:
你可以试试这个:
或者:
You could try this:
Or:
您应该避免使用
setTimeout
的字符串版本。我相信,在这种情况下,Javascript 正在寻找函数
window.editObject
而该函数不存在。您应该使用:
相反,因为这是在调用时获取对对象的引用,因此当超时到期时,该函数将可供 Javascript 调用
You should avoid using the string version of
setTimeout
.I believe that, in this case, Javascript is looking for the function
window.editObject
and this does not exist.You should use:
instead, as this is grabbing a reference to the object at call-time and so the function will be available to Javascript, for calling, when the timeout expires
直接使用函数引用(而不是在全局上下文中计算的字符串),如下所示:
Use the function reference directly (rather than a string, which is evaluated in a global context), like this:
更新:
我当然误解了这个问题,我的原始代码经过编辑后可以正常工作:
...
每当 Javascript 引擎尝试调用 jQuery 函数中定义的“editObject()”时,它就超出了 jQuery 函数的范围,它实际上位于全局作用域,但 editObject() 函数是在 jQuery 函数中定义的。
您可以在全局范围内创建 editObject 或创建对 jQuery 函数的引用并将其传递到 setTimeout 调用中,例如:
UPDATE:
I certainly misunderstood the problem, my original code edited to be working:
...
Whenever the Javascript engine will try to call "editObject()" defined in your jQuery function, it is out of your jQuery function's scope, it is actually in the global scope, but your editObject() function is defined in your jQuery function.
You can create the editObject in the global scope or create a reference to your jQuery function and pass it in your setTimeout call, like: