如何调用存储在 jQuery 数组中的函数?
我在 jQuery 中有一个钩子数组,它们在将数据加载到网格之前执行。然而,在一种情况下,我想删除该钩子,然后将其添加回来以供稍后使用。无论我在做什么都不能正常工作...这可能是一个语法错误,因为我对 jQuery 还有些陌生。任何帮助将不胜感激,谢谢!
当前代码:
var preLoad = this.opts.hooks.preLoad.pop();
//stuff happens
//now I want to add the preLoad hook back
this.opts.hooks.preLoad.push(function(report) { preLoad(report); });
编辑 事实证明问题出在代码的其他地方。但是,我仍然想知道如何最好地实现这一目标。
I have an array of hooks in jQuery that are executed before I load data into a grid. In one case, however, I want to remove the hook, then add it back for later. Whatever I'm doing is not working just right... it's probably a syntax error because I'm still somewhat new to jQuery. Any help would be appreciated, thanks!
Current code:
var preLoad = this.opts.hooks.preLoad.pop();
//stuff happens
//now I want to add the preLoad hook back
this.opts.hooks.preLoad.push(function(report) { preLoad(report); });
EDIT
It turns out the issue lies elsewhere in the code. However, I'd still like to know how best to accomplish this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以像访问任何其他数组中存储的任何其他变量一样访问它。
You access it the same way as any other variable stored in any other array.
你能不能像这样添加你删除的功能?
您确定它始终是您要删除的数组中的最后一个吗?
Can you not just add the function you removed like this?
And are you sure it's always the last one in the array that you want to remove?
这可能与以下事实有关:当您将函数推回堆栈时,您正在“罐装”参数“报告”。
尝试这样做:
我在这里测试了 http://jsfiddle.net/fWRez/
It probably has to do with the fact that you are "canning" the argument "report" when you push the function back on the stack.
Try doing it like that:
I've tested it here http://jsfiddle.net/fWRez/
您给出的示例与 jQuery 无关,是纯 Javascript。另外,请注意您在示例中所做的事情是......不正确的。考虑一下:
如果你执行这个:
你的
this.opts.hooks.preLoad
数组将如下所示:因为你每次执行代码时都会将函数包装到自身中。我不知道为什么你需要再次
pop
然后push
它,但这看起来很奇怪。此外,Javascript 是一种非常灵活的语言;这意味着你可以做很多奇怪的事情,比如
The example you gave has nothing to do with jQuery and is pure Javascript. Also, beware that what you are doing in your example is... not right. Consider this :
If you execute this :
Your
this.opts.hooks.preLoad
array will look like this :Because you are pushing the function wrapped into itself every time you execute your code. I'm not sure why you need to
pop
andpush
it back in again, but this just look odd.Also, Javascript is a very flexible language; which mean that you can do many weird stuff, like