基于Jquery、JqueryUI插件编写

刚开始编写jquery插件的时候,只是从网上找个模板看着写,并不理解.刚刚仔细把官网的API看了下,突然觉得豁然开朗了.马上放假了想着应该整理整理不然忘了又.

How to create a Jquery Plugin主要看的大体介绍,然后创建Basic Plugin 和  Advanced Plugin

Basic

1.这应该是最简单的一种,定义和调用

$.fn.greenify = function() {
    this.css( "color", "green" );
    return this; // chain use
}
 
$( "a" ).greenify().addClass( "greenified" );

2.proteting the $ Alias and Adding Scope(包起来防止$标识冲突)

(function ( $ ) {
 
    $.fn.greenify = function() {
        this.css( "color", "green" );
        return this;
    };

}( jQuery ));

3.Using the each() Method

调用插件方法时可能有多个Element

$.fn.myNewPlugin = function() {
 
    return this.each(function() {
        // Do something to each element here.
    });
 
};

Advanced

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

调用的时候有两种方式改变参数

// Override plugin default foreground color.
$.fn.hilight.defaults.foreground = "blue";
 
// ...
 
// 方式1.Invoke plugin using new defaults.
$( ".hilightDiv" ).hilight();
 
// ...
 
// 方式2.Override default by passing options to plugin method.
$( "#green" ).hilight({
    foreground: "green"
});

 

原文地址:https://www.cnblogs.com/kite-Runner/p/3532718.html