创建一个基本的 jQuery 插件

jQuery 如何工作

jQuery上的方法例如.css().click()都是从$.fn上获取的,$.fn包括了jQuery的所有方法。

基本插件

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

$( "a" ).greenify(); // Makes all the links green.

调用链

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

$( "a" ).greenify().addClass( "greenified" );

不要使用$以及作用域

(function ( $ ) {

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

}( jQuery ));

Minimizing Plugin Footprint

不要这样:

(function( $ ) {

    $.fn.openPopup = function() {
        // Open popup code.
    };

    $.fn.closePopup = function() {
        // Close popup code.
    };

}( jQuery ));

要这样:

(function( $ ) {

    $.fn.popup = function( action ) {

        if ( action === "open") {
            // Open popup code.
        }

        if ( action === "close" ) {
            // Close popup code.
        }

    };

}( jQuery ));

使用each()方法

如果你想操作元素的话,可以使用each()方法:

$.fn.myNewPlugin = function() {

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

};

接受参数

(function ( $ ) {

    $.fn.greenify = function( options ) {

        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            color: "#556b2f",
            backgroundColor: "white"
        }, options );

        // Greenify the collection based on the settings variable.
        return this.css({
            color: settings.color,
            backgroundColor: settings.backgroundColor
        });

    };

}( jQuery ));

results matching ""

    No results matching ""