2017年3月9日 星期四

基本的 jQuery 插件 - How to Create a Basic Plugin

Reference:
https://learn.jquery.com/plugins/basic-plugin-creation/
http://maidot.blogspot.tw/2011/04/jquery-this-this-different-between-this.html


1.創建一個基礎的jQuery plugin

-把我們創造的plugin加入至$.fn之中
(擴展$.fn.abc(),即$.fn.abc()是對jquery擴展了一個abc方法,那麼後面你的每一個jquery實例都可以引用這個方法了)
$.fn.greenify = function() {
    this.css( "color", "green" );
};
 
$( "a" ).greenify(); // Makes all the links green.

-注意這邊是使用css(),所以我們也用this,而非$(this),
因為在JQuery中this代表目前的DOM對象,$(this)代表我們用JQuery所選取的JQuery對象,
在上述方法中,this代表greenify(),而他與.css()都同屬同一個jQuery object的一部份


2.Chaining 讓自建jQuery plugin可與其他方法相連
新增一行『return this』把該jQuery Object 傳回
$.fn.greenify = function() {
    this.css( "color", "green" );
    return this;
}
 
$( "a" ).greenify().addClass( "greenified" );

3.確保plugin不會與其他JavaScript libraries產生衝突
(Protecting the $ Alias and Adding Scope)
在最外層多加一層$()宣告
(function ( $ ) {
 
    $.fn.greenify = function() {
        this.css( "color", "green" );
        return this;
    };
 
}( jQuery ));

4.讓一個plugin根據參數,做出不同的動作
(function( $ ) {
 
    $.fn.popup = function( action ) {
 
        if ( action === "open") {
            // Open popup code.
        }
 
        if ( action === "close" ) {
            // Close popup code.
        }
 
    };
 
}( jQuery ));

5.透過each(),對多個指定的DOM elements進行處理
$.fn.myNewPlugin = function() {
 
    return this.each(function() {
        // Do something to each element here.
    });
 
};
Notice that we return the results of .each() instead of returning this. Since .each() is already chainable, it returns this, which we then return. This is a better way to maintain chainability than what we've been doing so far.

.each() 方法,會遍歷jQuery對象中的每一個DOM元素
然後透過$(this) 將每一個取到的DOM變成jQuery Object
 return this.each(function() {
    var link = $(this);
    link.css("color", setting.color)
});
6.讓一個plugin接受『一組設定』
(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 ));
Example usage:
$( "div" ).greenify({
    color: "orange"
});

defaults 設定的顏色透過$.extend()把覆蓋成傳進來的值
The default value for color of #556b2f gets overridden by $.extend() to be orange.

7.完整範例
my_plugin.js
(function($) {

    $.fn.greenify = function(action, options) {
        var setting = $.extend({
            color: "green",
            backgroundColor: "white"
        }, options);

        if (action === 'div') {

            return this.css({
                color: setting.color,
                backgroundColor: setting.backgroundColor
            });
        };

        if (action === 'a') {
            return this.each(function() {
                var link = $(this);
                link.css("color", setting.color)
            });

        }

    };

}(jQuery));
template.html
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <script src="js/jquery-1.12.0.min.js"></script>
    <script src="js/my_plugin.js"></script>
    <script>
    $(document).ready(function() {
        $("a").greenify("a", {
            color: "red"
        });

        $("div").greenify("div", {
            color: "white",
            backgroundColor: "red"
        });
    });
    </script>
    <title>jQuery</title>

    <body>
        <a href="www.google.com.tw">GoogleGoog</a>
        <a href="www.yahoo.com.tw">YahooYahoo</a>
        <div>
            Hello
        </div>
    </body>

</html>

沒有留言:

張貼留言