Lenny-Hu / note

blog
5 stars 1 forks source link

如何写jQuery插件 #43

Open Lenny-Hu opened 5 years ago

Lenny-Hu commented 5 years ago

参考

Lenny-Hu commented 5 years ago

写法1

;(function ($, window, document, undefined) {
  // 注册的插件名称
  var pluginName = 'lottery';
  // 默认参数
  var defaults = {

  };
  // 构造函数
  function Lottery(element, options) {
    this.element = element;
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.version = 'v1.0.0';
    this.init();
  }
  // 初始化方法
  Lottery.prototype.init = function () {
    // 初始化的一些事
    $(this.element).on('click', function () {
      console.log('hello world');
    })
  }

  $.fn[pluginName] = function (options) {
    // 处理多个元素,虽然可能插件只会操作一个元素
    this.each(function() {
      // each 内的this指向当前的dom元素,非jQuery对象 
      // 防止再次初始化
      if (!$.data(this, 'plugin_' + pluginName)) {
        $.data(this, 'plugin_' + pluginName, new Lottery(this, options));
      }
    });

    return this; // 保持可以链式操作的风格
  }
})(jQuery, window, document);

// 调用
$('body').lottery();
Lenny-Hu commented 5 years ago

写法2

;(function ($) {
  // Plugin definition.
$.fn.hilight = function( options ) {

    // Extend our default options with those provided.
    // Note that the first argument to extend is an empty
    // object – this is to keep from overriding our "defaults" object.
    var opts = $.extend( {}, $.fn.hilight.defaults, options );

    // Our plugin implementation code goes here.

};

// Plugin defaults – added as a property on our plugin function.
$.fn.hilight.defaults = {
    foreground: "red",
    background: "yellow"
};
})(jQuery)

// This needs only be called once and does not
// have to be called from within a "ready" block
$.fn.hilight.defaults.foreground = "blue";

$( "#myDiv" ).hilight();
Lenny-Hu commented 5 years ago

其它写法

// 全局
jQuery.myAlert=function (str) {
    alert(str);
};

jQuery.myAlert(123);

// 命名空间
jQuery.yuqing={
    myAlert4:function (str) {
        alert(str);
    },
    centerWindow:function (obj) {
        obj.css({
            'top':($(window).height()-obj.height())/2,
            'left':($(window).width()-obj.width())/2
        });
        //必须进行返回对象的操作,否则就不能继续往下进行链式操作了。。
        return obj;
    }
};

扩展jQuery对象本身,用来在jQuery命名空间上增加新函数

jQuery.extend({
  min: function(a, b) { return a < b ? a : b; },
  max: function(a, b) { return a > b ? a : b; }
});

jQuery.min(2,3); // => 2
jQuery.max(4,5); // => 5

扩展 jQuery 元素集来提供新的方法(通常用来制作插件)

jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});

$("input[type=checkbox]").check();
$("input[type=radio]").uncheck();