建立簡單的jquery外掛程式

來源:互聯網
上載者:User

建立簡單的jquery外掛程式


1、建立基本外掛程式的通用方法:

 

$.fn.greenify = function() {    this.css( "color", "green" );}; $( "a" ).greenify();
2、增加鏈式的調用:在上面的方法中增加this的返回
$.fn.greenify = function() {    this.css( "color", "green" );    return this;} $( "a" ).greenify().addClass( "greenified" );
3、保護js命名空間的乾淨 減少和其他的外掛程式的汙染, 避免和別的外掛程式的$的衝突,我們需要把我們的代碼放在一個立即調用的函數運算式內

 

然後傳遞jQuery,參數命名為$

 

(function ( $ ) {     $.fn.greenify = function() {        this.css( "color", "green" );        return this;    }; }( jQuery ));
另外,立即調用函數的主要目的是允許我們使用我們的私人變數,可以把值儲存在一個變數中

 

這樣就可以在立即調用函數中定義私人變數而不汙染公用環境

 

(function ( $ ) {     var shade = "#556b2f";     $.fn.greenify = function() {        this.css( "color", shade );        return this;    }; }( jQuery ));
儘可能的定義在一個方法內
(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 ));


4、如果擷取的是一個dom集合,想操作其中的合格元素使用.each()的方法迴圈這個dom集合,返回的操作修改後的元素集,以供繼續調用方法

 

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

 

 

5、擴充參數:使用自訂的參數 覆蓋預設的參數 $.extend(settings,options);
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 ));
$( "div" ).greenify({    color: "orange"});
以下是以上的綜合樣本:
<script type="text/javascript" src="js/jquery-1.11.1.js"></script><script type="text/javascript">(function($){$.fn.greenify = function(options){var settings = $.extend({color:"green",backgroundColor:"black"},options);var that = this;return that.each(function(){$(this).css({color:settings.color,backgroundColor:settings.backgroundColor});});};})(jQuery);$(function(){$("a:lt(2)").greenify({color:"orange"}).html(111);});</script>This is my HTML page.

dianji dianji11 dianji221

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.