Jquery:我有一个函数$ .fn.my_function,里面有其他函数,我怎么称呼它们?

ape*_*ari 6 jquery function extend

假设我有这个($ = jquery):

 $.fn.my_function = function() {
    function foo() 
    { 
       //do something 
    };

    function bar() 
    { 
       //do something other
    };

 }
Run Code Online (Sandbox Code Playgroud)

我这么做了 $('.my_class').my_function();

现在,我需要在回调某些事件时调用foo和bar.

我怎么称呼他们?

TM.*_*TM. 7

你不得不以某种方式将它们暴露给"外部世界".目前,它们仅在内部可见,my_function因此您无法从其他任何地方呼叫它们.

最天真的解决方法是:

var foo;
var bar;
$.fn.my_function = function() {
    foo = function() {
       //stuff
    };
    bar = function() {
       //stuff
    };
};
Run Code Online (Sandbox Code Playgroud)

可以应用相同的概念将引用放在任何对您的使用有意义的地方.


ant*_*i_s 7

看来你正在尝试构建一个jQuery插件.您应该将插件的方法约束到私有范围,并且还应该通过jQuery选择器迭代给插件的元素,并使用jQuery的"each"返回它们以保留链接能力:

// wrap the plugin code inside an anonymous function 
// to keep the global namespace clean   
(function($){
    $.fn.my_function = function() {
        return this.each(function(){
            function foo() {
                // stuff here
            }
            function bar() {
                // stuff here
            }
            // now you can use your foo and bar which ever way you want
            // inside the plugin
            $(this).focus(function(event){
                // do some stuff
                ...
                // call the function defined previously in the plugin code
                foo(); 
            });
            $(this).blur(function(event){
                // do some stuff
                ...
                // call the function defined previously in the plugin code
                bar();
            });
        });
    };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

有关jQuery插件开发的更多信息,您可能需要查看这些文章:http: //www.learningjquery.com/2007/10/a-plugin-development-pattern

http://docs.jquery.com/Plugins/Authoring

但是,如果你只是做一些"实用程序"类型的函数,你可以将它们绑定到jQuery命名空间,如下所示:

$.foo = function(){
         // do stuff
    };
$.bar = function(){
        // do stuff
    };
Run Code Online (Sandbox Code Playgroud)