0

我知道,网上有很多例子,但是对于初学者来说很难从中找到一个真正的例子。所以我想用公共方法创建 jQuery 插件。示例代码:

(function($) {
    $.fn.peel = function(options) {
        var defaults = {
        };

        var settings = $.extend({},defaults, options);

        this.public = function() {
            alert("public");
        };

        var private = function() {
            alert("private");
        }

        return this.each(function() {
            //this.public();
            private();
        });
    };
})(jQuery);

正如我发现的那样,这是制作公共功能的方法,可以这样调用:

var peel = $('img').peel();
peel.public();

到目前为止它按预期工作 - 可以调用 public() 。但是如果我想在我的插件中调用那个函数呢?我在 this.each() 中注释掉了,因为它不起作用。我怎样才能做到这一点?

4

1 回答 1

1

One way to create publicly accessible methods within your plugins is to use the jQuery UI widget factory. This is the framework that jQuery UI uses for all of it's supported UI widgets. A quick example would look like this:

(function( $ ) {
    $.widget( "something.mywidget", {

    // Set up the widget
    _create: function() {

    },

    publicFunction: function(){
        //...
    }
  });
}( jQuery ) );

var $w = $('#someelement').mywidget();

$w.mywidget('publicFunction');
于 2013-01-10T22:37:04.550 回答