Jquery:我有一个函数 $.fn.my_function ,里面有其他函数,我该如何调用它们?
假设我有这个($ = jquery):
$.fn.my_function = function() {
function foo()
{
//do something
};
function bar()
{
//do something other
};
}
我用 $('.my_class').my_function();
启动它
现在,我需要在某些事件的回调中调用 foo 和 bar 。
我该如何称呼他们?
Suppose i have this ($ = jquery):
$.fn.my_function = function() {
function foo()
{
//do something
};
function bar()
{
//do something other
};
}
I lauch this with $('.my_class').my_function();
Now, i need to call foo and bar on callback to certain events.
How can i call them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你必须以某种方式将他们暴露给“外部世界”。目前,它们仅在
my_function
中可见,因此您无法从其他任何地方调用它们。解决这个问题的最简单的方法是这样的:
可以应用相同的概念来将对它们的引用放置在对您的使用有意义的任何地方。
You'll have to expose them to the "outside world" somehow. Currently, they are only visible within
my_function
so you won't be able to call them from anywhere else.The most naive way to fix this would be something like:
The same concept could be applied to place references to them anywhere that makes sense for your usage.
您似乎正在尝试构建一个 jQuery 插件。您应该将插件的方法限制在私有范围内,并且还应该迭代 jQuery 选择器提供给插件的元素,并使用 jQuery 的“each”返回它们以保留链接功能:
您可能想看看有关 jQuery 插件开发的更多信息,请阅读以下文章:
http://www.learningjquery.com/2007/10/a-plugin -development-pattern
http://docs.jquery.com/Plugins/Authoring
但是,如果您只执行一些“实用”类型的函数,则可以将它们绑定到 jQuery 命名空间,如下所示:
It seems that you're trying to build a jQuery plugin. You should constrain your plugin's methods to a private scope, and you should also iterate over the elements given to the plugin by the jQuery selector, and return them by using jQuery's "each" to preserve the chaining abilities:
You might wanna have a look at these articles for more info on jQuery plugin development:
http://www.learningjquery.com/2007/10/a-plugin-development-pattern
http://docs.jquery.com/Plugins/Authoring
However, if you're doing just some "utility"-type functions, you can just tie them to jQuery namespace like this:
HTML
JS
HTML
JS
处理这种情况的另一种方法,如果您想从其他地方(可能是不同的文件等)调用插件的方法,这很有用,即将插件逻辑编写为类,然后在 jQuery 插件中实例化该类,存储实例在
$.data
中。然后当你想调用你的插件时,就像平常一样:
调用一个方法:
Another way to handle this situation, which is useful if you want to call your plugin's methods from elsewhere (perhaps a different file etc.) is to write the plugin logic as a class and then instantiate that class inside the jQuery plugin, storing the instance in
$.data
.Then when you want to call your plugin, it's just like normal:
and call a method: