如何在jQuery插件中创建一个公共方法

How to make a public method in jQuery Plugin

本文关键字:一个 方法 jQuery 插件 创建      更新时间:2023-09-26

我一直在使用下面的样板用于jQuery插件的开发,它运行得很好。但我不确定公开"方法"的最佳方式。

           ;(function ( $, window, undefined ) {
              var pluginName = 'defaultPluginName',
                  document = window.document,
                  defaults = {
                    propertyName: "value"
                  };
              function Plugin( element, options ) {
                this.element = element;
                this.options = $.extend( {}, defaults, options) ;
                this._defaults = defaults;
                this._name = pluginName;
                this.init();
              }
              Plugin.prototype.init = function () {
              };
              $.fn[pluginName] = function ( options ) {
                return this.each(function () {
                  if (!$.data(this, 'plugin_' + pluginName)) {
                    $.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
                  }
                });
              }
            }(jQuery, window));

感谢

只有函数可以是私有/本地的,而不是jQuery插件。

如果您正在使用jQuery并试图在jQuery中添加您自己的(自定义)函数,则有一种最佳方式jQuery.fn.yourFunctionname = function(){},因为jQuery已经在公共范围中,所以jQuery.fn.yourFunctionname是公共范围(无论您在哪里定义插件,都可以全局使用)。

window.jQuery = jQuery;

$.fn.pluginName = function ( options ) {
    return this.each(function () {
    // code goes here
    });
}