Jquery插件制作小知识

首先要理解基础的知识点:
1.(function(){ })(jQuery);的理解

(function(){ })(jQuery);

执行()(para)匿名方法,只不过是传递了jQuery对象,类似于

function aa($){} 
aa(jQuery)

是初始化jquery对象的惯用方法。
在页面DOM加载完成后(不包括图片下载完成)执行你需要的代码,由于不包括图片下载,所以比window.onload效率高。
不过这个东西,有的时候会使页面跳动,很多JQUERY插件都是在加载完成后,才改变样式的,页面会有跳动或闪动的感觉.
用于存放开发插件的代码,执行其中代码时DOM不一定存在,所以直接自动执行DOM操作的代码请小心使用。
2.$.fn的的用法
.fnjqueryfnjquery .fn.test(),即 .fn.test()jquerytest,jquery.使 (“#div”).test();

jQuery为开发插件提拱了两个方法,分别是:

jQuery.extend(object);为扩展jQuery类本身.为类添加新的方法。
jQuery.fn.extend(object);给jQuery对象添加方法。
3.defaults是默认的参数
也就是你往这个插件里面不传参数直接调用的话,插件用的就是默认里面的数值

开发插件的格式如下:

(function ($) {
        $.fn.test = function () {
            alert('test')
        }
    })(jQuery);

调用插件的方法

$("#elementid").test();

实例:

链接:http://caibaojian.com/279.html
来源:http://caibaojian.com

// 创建一个闭包
(function($) {
  // 插件的定义
  $.fn.hilight = function(options) {
    debug(this);
    // build main options before element iteration(迭代)
    var opts = $.extend({}, $.fn.hilight.defaults, options);
    // iterate and reformat(重定格式) each matched(匹配的) element
    return this.each(function() {
      $this = $(this);
      // build element specific options
      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
      // update element styles
      $this.css({
        backgroundColor: o.background,
        color: o.foreground
      });
      var markup = $this.html();
      // call our format(格式) function
      markup = $.fn.hilight.format(markup);
      $this.html(markup);
    });
  };
  // 私有函数:debugging
  function debug($obj) {
    if (window.console && window.console.log)
      window.console.log('hilight selection count: ' + $obj.size());
  };
  // 定义暴露format函数
  $.fn.hilight.format = function(txt) {
    return '<strong>' + txt + '</strong>';
  };
  // 插件的defaults
  $.fn.hilight.defaults = {
    foreground: 'red',
    background: 'yellow'
  };
// 闭包结束
})(jQuery);

猜你喜欢

转载自blog.csdn.net/weixin_40682842/article/details/78749890
今日推荐