Jquery 外掛程式入門

來源:互聯網
上載者:User

網上一搜各種外掛程式,什麼檔案上傳,圖片瀏覽 ,Autocomplete等 這些外掛程式,原始碼,新手看起來是很吃力的,當然我也是新手,我開始改AutoComplete這個外掛程式一點點,卻真不知道如何開始,後面就用Firefox的fireDebug慢慢看。 我也不是專門做前端的,但是總得瞭解,基本的使用還是得會。   今天,來總結下,最近看的外掛程式的基礎知識,這裡算個入門,希望能幫到新手黨們。 下面是2個非常重要的擴充函數。 .extend and.fn.extend $.extend(object) 可以理解為JQuery 添加一個靜態方法。 $.fn.extend(object) 可以理解為JQuery執行個體添加一個方法。 基本的定義與調用: 複製代碼/* $.extend 定義與調用 */$.extend({ fun1: function () { alert("執行方法一"); } });$.fun1();/*  $.fn.extend 定義與調用 */$.fn.extend({ fun2: function () { alert("執行方法2"); } });$(this).fun2();//等同於$.fn.fun3 = function () { alert("執行方法三"); }$(this).fun3();複製代碼  $.extend(target, [object1], [objectN]) 還有個用法,就是合并到第一個object. 該方法主要用於合并兩個或更多個物件的內容(屬性)到第一個對象,並返回合并後的第一對象。如果該方法只有一個參數target,則該參數將擴充jQuery的命名空間,即作為靜態方法掛在jQuery全域對象下,如jQuery裡的$.ajax、$.getJSON全域函數等,如前面看到的: 值得注意的是:多個對象參數合并時,會破壞第一個對象的結構,所以可傳遞一個Null 物件作為第一個參數,如:$.extend({}, object1, object2);  var options = $.extend({},defaults, options);  上面代碼就是合并到{}中,然後賦值到options。這個在寫外掛程式的時候經常使用,使用者可以自己定義某些屬性, 外掛程式一般也會定義預設屬性,調用上面方法後,如果自訂屬性,這使用新屬性,否則,則使用預設屬性,這個是非常有用的。   $.fn.extend(target) 在jQuery中,.fn本質上是等於jQuery的原型,即.fn = $.prototype, 所以該方法實際上是為jQuery原型添加方法,即把target對象的方法添加到jQuery原型中去,這樣jQuery對象執行個體就可以訪問添加的方法了,這也是jQuery外掛程式開發常用的方法,特別是添加多個介面時。如: // 將hello、hello2方法添加到jquery原型中$.fn.extend({     hello: function() {alert("hello!");},    hello2: function() {alert("hello again!);}});看看Autocomplete外掛程式使用的該方法。  $.fn.extend({    autocomplete: function(urlOrData, options) {        var isUrl = typeof urlOrData == "string";        options = $.extend({}, $.Autocompleter.defaults, {            url: isUrl ? urlOrData : null,            data: isUrl ? null : urlOrData,            delay: isUrl ? $.Autocompleter.defaults.delay : 10            max: options && !options.scroll ? 1000 : 15000        }, options);                // if highlight is set to false, replace it with a do-nothing function        options.highlight = options.highlight || function(value) { return value; };                // if the formatMatch option is not specified, then use formatItem for backwards compatibility        options.formatMatch = options.formatMatch || options.formatItem;                return this.each(function() {            new $.Autocompleter(this, options);        });    },    result: function(handler) {        return this.bind("result", handler);    },    search: function(handler) {        return this.trigger("search", [handler]);    },    flushCache: function() {        return this.trigger("flushCache");    },    setOptions: function(options){        return this.trigger("setOptions", [options]);    },    unautocomplete: function() {        return this.trigger("unautocomplete");    }}); 看不懂?沒關係,下面馬來接上。   如果添加單個方法到jQuery原型中,可使用$.fn.pluginName方法添加,如: // 將hello方法添加到jquery原型中$.fn.hello = function() {    // ...            };     外掛程式通用模板(單個方法): 外掛程式有自己的基本格式:  ;(function($){    $.fn.yourName = function(options){        //各種屬性、參數        }        var options = $.extend(defaults, options);        return this.each(function(){        //外掛程式實現代碼        });    };})(jQuery);  上面代碼的最前面有一個分號,這是為了防止多個指令檔合并時,其他指令碼的結尾語句沒有添加分號,造成執行階段錯誤。   1、把全部代碼放在閉包(一個即時執行函數)裡 此時閉包相當於一個私人範圍,外部無法訪問到內部的資訊,並且不會存在全域變數的汙染情況。官方建立開發規範的解釋是: a) 避免全域依賴; b) 避免第三方破壞; c) 相容jQuery操作符'$'和'jQuery '。 如下所示: (function($) {    // 局部範圍中使用$來引用jQuery    // ...})(jQuery);  這段代碼在被解析時可理解成以下代碼: var jQ = function($) {  // code goes here}; jQ(jQuery);  新手如果無法理解,你知道,這是官方標準就ok。   下面是這個美化表格的例子,實現原理倒是簡單,無非就是找到表格的奇偶行,然後添加不同的class,活動行高亮顯示也很簡單,只要判斷mouseover事件,然後添加一個class,mouseout的時候,再去掉這個class即可。   查看這個連結能看到詳細,你可以查看具體看看,寫的不錯,特別是步驟很清晰。   好,基本架構曉得了,下面就是填充具體內容了。 複製代碼(function($){    $.fn.tableUI = function(options){        var defaults = {            evenRowClass:"evenRow",            oddRowClass:"oddRow",            activeRowClass:"activeRow"                    }        var options = $.extend({},defaults, options);        this.each(function(){            //實現代碼        });    };})(jQuery);   重複一句: var options = $.extend({},defaults, options);其實就是合并多個對象為一個。這裡就是,如果你在調用的時候寫了新的參數,就用你新的參數,如果沒有寫,就用預設的參數。想進一步瞭解的朋友,可以參考jquery的官方文檔: http://api.jquery.com/jQuery.extend/   其實,這裡定義預設 var defaults是不規則的寫法, 規則該是這樣  $.fn.TableUI.defaults={      evenRowCass: "evenRow",   oddRowClass: "oddRow",  activeRowClass: "activeRow"}; options = $.extend({},$.fn.TableUI.defaults,options);   好了,直接看全部代碼:  //這裡最好寫上相關描述,如時間,作者,主要用於幹什麼/* * tableUI 0.1 * Copyright (c) 2009 JustinYoung  http://justinyoung.cnblogs.com/ * Date: 2010-03-30 * 使用tableUI可以方便地將表格提示使用體驗。先提供的功能有奇偶行顏色交替,滑鼠移上高亮顯示 */ ;(function($){    $.fn.tableUI = function(options){  $.fn.TableUI.defaults={     evenRowCass: "evenRow",     oddRowClass: "oddRow",    activeRowClass: "activeRow"  };        var options = $.extend({}, $.fn.TableUI.defaults, options); //合并        return this.each(function(){            var thisTable=$(this);            //添加奇偶行顏色            $(thisTable).find("tr:even").addClass(options.evenRowClass);            $(thisTable).find("tr:odd").addClass(options.oddRowClass);            //添加活動行顏色            $(thisTable).find("tr").bind("mouseover",function(){                $(this).addClass(options.activeRowClass);            });            $(thisTable).find("tr").bind("mouseout",function(){                $(this).removeClass(options.activeRowClass);            });        });    };})(jQuery);  下面是調用代碼。   <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>    <script src="Scripts/TableUI.js" type="text/javascript"></script>    <script type="text/javascript">        $(document).ready(function () {            $(".table_solid").TableUI({ evenRowCass: "eventRow", oddRowClass: "oddRowClass", activeRowClass: "activeRow" }); //這裡是輸入新的參數,不使用預設參數。外掛程式代碼會自動覆蓋。        })    </script>    <style type="text/css">        body        {            font-family: 'Verdana' , '宋體';            font-size: 12px;        }        .eventRow        {            background-color: #f0f0ff;        }        .activeRow        {            background-color: #FFFF55;        }        .oddRowClass        {            background-color: red;        }    </style>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.