再談:jquery編寫外掛程式的方法

來源:互聯網
上載者:User

標籤:

著作權聲明:作者原創,轉載請註明出處!

編寫外掛程式的兩種方式:

  1.類層級開發外掛程式(1%)

  2.對象層級開發(99%)

類層級的靜態開發就是給jquery添加靜態方法,三種方式

  1.添加新的全域函數

  2.使用$.extend(obj)

  3.使用命名空間

類層級開發外掛程式(用的非常少,1%)

  分別舉例:

//1.直接給jquer添加全域函數jQuery.myAlert=function (str) {    alert(str);};//2.用extend()方法。extend是jquery提供的一個方法,把多個對象合并起來,參數是objectjQuery.extend({    myAlert2:function (str1) {        alert(str1);    },    myAlert3:function () {        alert(11111);    }});//一定要注意兩種類層級編寫外掛程式方式書寫的區別。//3.使用命名空間(如果不使用命名空間容易和其他引入的JS庫裡面的同名方法衝突)jQuery.yuqing={    myAlert4:function (str) {        alert(str);    },    centerWindow:function (obj) {        obj.css({            ‘top‘:($(window).height()-obj.height())/2,            ‘left‘:($(window).width()-obj.width())/2        });        //必須進行返回對象的操作,否則就不能繼續往下進行鏈式操作了。。        return obj;    }};

調用部分:

  //調用自訂外掛程式方法  $(‘#btn‘).click(function () {      $.myAlert(‘我是調用jquery編寫的外掛程式彈出的警告框‘);      $.myAlert2(‘我是調用jquery的extend()方法編寫的外掛程式彈出的警告框‘);      $.myAlert3();      $.yuqing.myAlert4("調用使用了命名空間編寫的外掛程式方法");  }); $.yuqing.centerWindow($(‘#div1‘)).css(‘background‘,‘red‘);

注意:jquery檔案要一併引入。

對象層級開發外掛程式(常用99%)

jquery官方給了一套對象層級開發外掛程式的模板:

;(function ($) {    $.fn.plugin=function (options) {        var defaults={            //各種參數、各種屬性        };
//options合并到defaults上,defaults繼承了options上的各種屬性和方法,將所有的賦值給endOptions var endOptions=$.extend(defaults,options); this.each(function () { //實現功能的代碼 }); };})(jQuery);

模板要點:

1.函數全部放在閉包裡,外面的函數就調用不到裡面的參數了,比較安全
2.前面加分號,避免不必要的麻煩

舉個栗子:

  需求:開發一個外掛程式,要求奇數行顏色是yellow,偶數行顏色是green,滑鼠移到的行變為blue,移除變為原來的顏色

   HTML布局:

 View Code

  css樣式

 View Code

  jquery調用代碼:

$(‘#tab‘).table({    evenRowClass:‘evenRow1‘,    oddRowClass:‘oddRow1‘,    curRowClass:‘curRow1‘,    eventType1:‘click‘});

 jquery外掛程式代碼:

 1 ;(function ($) { 2     $.fn.table=function (options) { 3         var defaults={ 4             //各種參數、各種屬性 5             evenRowClass:‘evenRow‘, 6             oddRowClass:‘oddRow‘, 7             curRowClass:‘curRow‘, 8             eventType1:‘mouseover‘, 9             eventType2:‘mouseout‘10         };11         12         var endOptions=$.extend(defaults,options);13         14         this.each(function () {15             var _this = $( this );16             _this.find(‘tr:even‘).addClass(endOptions.evenRowClass);17             _this.find(‘tr:odd‘).addClass(endOptions.oddRowClass);
18 //滑鼠移入和移出,但實際開發中不直接使用mouseover這種方法19 /*$(this).find(‘tr‘).mouseover(function () {20 $(this).addClass(endOptions.curRowClass);21 }).mouseout(function () {22 $(this).removeClass(endOptions.curRowClass);23 });*/24 25 //實際開發中要用bian()方法綁定26 //因為用bind()方法綁定非常靈活,事件可以自己定義27 //mouseover mouseout...事件底層都是用bind()去實現的,mouseout 等只是捷徑28 _this.find(‘tr‘).bind(endOptions.eventType1,function () {29 $(this).addClass(endOptions.curRowClass);30 });31 _this.find(‘tr‘).bind(endOptions.eventType2,function () {32 $(this).removeClass(endOptions.curRowClass);33 })34 });35 };36 })(jQuery);

外掛程式注釋:

15行:var _this = this;  變數儲存,因為很多地方用到$(this);所以將其儲存為變數使用更加的方便,也提高了運行效率。

19-23行與28-33行實現的功能是相同的,但是推薦使用28-33行的寫法,使用bian()進行事件的綁定,因為使用會非常的靈活。

可變的地方,如樣式名稱等最好寫在defaults裡,方便使用者自行配置。

 

再來一個對象層級實現jquery外掛程式的栗子(⊙o⊙)哦!!實現選項卡功能~~

HTML布局

<div id="tab">    <ul id="nav">        <li class="active">HTML</li>        <li>CSS</li>        <li>JAVASCRIPT</li>    </ul>    <div id="cont">        <div style="display: block;">HTML</div>        <div>CSS</div>        <div>JAVASCRIPT</div>    </div></div>

css樣式:

* {    margin: 0;    padding: 0;}#nav li {    list-style: none;    float: left;    height: 25px;    line-height: 25px;    border: 1px solid #0000FF;    border-bottom: none;    padding: 5px;    margin: 10px;    margin-bottom: 0;}#cont div {    width: 210px;    height: 150px;    border: 1px solid #0000FF;    margin-left: 10px;    clear: both;    display: none;}.active {    background: #AFEEEE;}

調用的JS代碼

<script type="text/javascript">    $(‘#tab‘).tab({        tabType: ‘mouseover‘    });</script>

注意哦:不要忘記先引入jquery.js檔案喔,然後在引入我們編寫的外掛程式tab.js,才能正確調用到tab()方法。。。

外掛程式tab.js

;(function($) {    $.fn.tab = function(options) {        var defaults = {            tabActiveClass: ‘active‘,            tabNav: ‘#nav>li‘,            tabCont: ‘#cont>div‘,            tabType: ‘click‘        };        var endOptions = $.extend(defaults, options);        $(this).each(function() {            var _this = $(this);            _this.find(endOptions.tabNav).bind(endOptions.tabType, function() {                $(this).addClass(endOptions.tabActiveClass).siblings().removeClass(endOptions.tabActiveClass);                var index = $(this).index();                _this.find(endOptions.tabCont).eq(index).show().siblings().hide();            });        });    };})(jQuery);

這個小栗子和上一個表格外掛程式的栗子相似性是很高的,多敲幾遍,理解意思,其實jquery擴充外掛程式並不難哦~~

 

再談:jquery編寫外掛程式的方法

聯繫我們

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