Jquery:我有一个函数 $.fn.my_function ,里面有其他函数,我该如何调用它们?

发布于 2024-08-11 02:10:51 字数 323 浏览 7 评论 0原文

假设我有这个($ = 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

_蜘蛛 2024-08-18 02:10:52

你必须以某种方式将他们暴露给“外部世界”。目前,它们仅在 my_function 中可见,因此您无法从其他任何地方调用它们。

解决这个问题的最简单的方法是这样的:

var foo;
var bar;
$.fn.my_function = function() {
    foo = function() {
       //stuff
    };
    bar = function() {
       //stuff
    };
};

可以应用相同的概念来将对它们的引用放置在对您的使用有意义的任何地方。

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:

var foo;
var bar;
$.fn.my_function = function() {
    foo = function() {
       //stuff
    };
    bar = function() {
       //stuff
    };
};

The same concept could be applied to place references to them anywhere that makes sense for your usage.

如梦亦如幻 2024-08-18 02:10:52

您似乎正在尝试构建一个 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);

您可能想看看有关 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
    };

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:

// 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);

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:

$.foo = function(){
         // do stuff
    };
$.bar = function(){
        // do stuff
    };
把梦留给海 2024-08-18 02:10:52

HTML

<p id="hello">aaa</p>
<p id="hola">sss</p>
<div id='result'></div>

JS

$.fn.my_function = function() 
{
    this.foo = function(xref) {
       $("#result").append("<div>"+xref+".foo " + $(this).html() +"</div>");
    };

    this.bar = function(xref) {
       $("#result").append("<div>"+xref+".bar " + $(this).html() +"</div>");
    };

    return this;
};

var ee1 = $("#hello").my_function();
var ee2 = $("#hola").my_function();

ee1.bar("ee1");
ee2.bar("ee2");
$("#hello").html("hello hellboy");
ee1.foo("ee1");
ee2.foo("ee2");
$("#result").append("<hr />");
ee1.bar("ee1");
ee2.bar("ee2");
$("#hola").html("hola hellboy");
ee1.foo("ee1");
ee2.foo("ee2");

HTML

<p id="hello">aaa</p>
<p id="hola">sss</p>
<div id='result'></div>

JS

$.fn.my_function = function() 
{
    this.foo = function(xref) {
       $("#result").append("<div>"+xref+".foo " + $(this).html() +"</div>");
    };

    this.bar = function(xref) {
       $("#result").append("<div>"+xref+".bar " + $(this).html() +"</div>");
    };

    return this;
};

var ee1 = $("#hello").my_function();
var ee2 = $("#hola").my_function();

ee1.bar("ee1");
ee2.bar("ee2");
$("#hello").html("hello hellboy");
ee1.foo("ee1");
ee2.foo("ee2");
$("#result").append("<hr />");
ee1.bar("ee1");
ee2.bar("ee2");
$("#hola").html("hola hellboy");
ee1.foo("ee1");
ee2.foo("ee2");
泪痕残 2024-08-18 02:10:52

处理这种情况的另一种方法,如果您想从其他地方(可能是不同的文件等)调用插件的方法,这很有用,即将插件逻辑编写为类,然后在 jQuery 插件中实例化该类,存储实例在$.data中。

(function($) {

  var Animal = function(el, settings) {
    this.$el = $(el);
    this.settings = settings;

    this.foo();
  };

  Animal.prototype.eat = function() {
    // Do stuff
    if (this.settings.isVegetarian) {
      console.log('I eat plants');
    } else {
      console.log('I eat meat');
    }
  };

  Animal.prototype.play = function() {
    // Do other stuff but return this.$el so you can maintain chain
    return this.$el;
  };

  // Create jQuery plugin
  var pluginName = 'myPlugin';

  $.fn[pluginName] = function(options) {
    // Defaults
    var settings = $.extend({
      isVegetarian: true,
    }, options );

    return this.each(function() {
      if (!$.data(this, pluginName)) {
        // Store plugin instace with element (this), 
        // so public methods can be called later: 
        // $('.el').data('myPlugin').eat();
        $.data(this, pluginName, new Animal(this, settings));
      }
    });
  };

}(jQuery));

然后当你想调用你的插件时,就像平常一样:

$('.dog).myPlugin();

调用一个方法:

$('.dog').data('myPlugin').eat();

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.

(function($) {

  var Animal = function(el, settings) {
    this.$el = $(el);
    this.settings = settings;

    this.foo();
  };

  Animal.prototype.eat = function() {
    // Do stuff
    if (this.settings.isVegetarian) {
      console.log('I eat plants');
    } else {
      console.log('I eat meat');
    }
  };

  Animal.prototype.play = function() {
    // Do other stuff but return this.$el so you can maintain chain
    return this.$el;
  };

  // Create jQuery plugin
  var pluginName = 'myPlugin';

  $.fn[pluginName] = function(options) {
    // Defaults
    var settings = $.extend({
      isVegetarian: true,
    }, options );

    return this.each(function() {
      if (!$.data(this, pluginName)) {
        // Store plugin instace with element (this), 
        // so public methods can be called later: 
        // $('.el').data('myPlugin').eat();
        $.data(this, pluginName, new Animal(this, settings));
      }
    });
  };

}(jQuery));

Then when you want to call your plugin, it's just like normal:

$('.dog).myPlugin();

and call a method:

$('.dog').data('myPlugin').eat();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文