English 中文(简体)
Jquery: i have a function $.fn.my_function with other functions inside, how can i call them?
原标题:

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?

最佳回答

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.

问题回答

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
    };

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

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




相关问题
getGridParam is not a function

The HTML: <a href="javascript:void(0)" id="m1">Get Selected id s</a> The Function: jQuery("#m1").click( function() { var s; s = jQuery("#list4").getGridParam( selarrrow )...

selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

jQuery cycle page with links

I am using the cycle plugin with pager functionality like this : $j( #homebox ) .cycle({ fx: fade , speed: fast , timeout: 9000, pager: #home-thumbs , ...

jquery ui dialog opens only once

I have a button that opens a dialog when clicked. The dialog displays a div that was hidden After I close the dialog by clicking the X icon, the dialog can t be opened again.

jConfirm with this existing code

I need help to use jConfirm with this existing code (php & Jquery & jAlert). function logout() { if (confirm("Do you really want to logout?")) window.location.href = "logout.php"; } ...

Wrap text after particular symbol with jQuery

What I m trying to do, is wrap text into div inside ll tag. It wouldn t be a problem, but I need to wrap text that appears particularly after "-" (minus) including "minus" itself. This is my html: &...

热门标签