撰寫jQuery的plugin

1.開始撰寫

撰寫jQuery的外掛的第一步就是用fn延伸出一個方法,如accordion,再定義一個方法即可。

jQuery.fn.accordion=function(){};

 

2.避免$符號與其他的javascript library衝突

(function($){
$.fn.accordion=function(){};
})(jQuery);

 

3.讓自訂的plugin能夠串接其他的jQuery方法

(function($){
$.fn.accordion=function(){
  return this.each(function(){
    
  });
};
})(jQuery);

 

4.撰寫html及css進行測試

css檔

            .accordion{
                width:500px;
                border:1px solid #ccc;
                border-bottom:none;
                font-family:Arival,Helvetica,sans-serif;
                font-size:12px;
            }
            
            .accordion dt,.accordion dd{
                border-bottom:1px solid #ccc;
                margin:0px;
            }
            
            .accordion dt{
                background: #eaeaea;
                cursor:pointer;
                padding:8px 4px;
                font-size:13px;
                font-weight: bold;
            }
            
            .accordion dd{
                padding:12px 8px;
            }

 

html檔案

        <dl class="accordion" id="my-accordion">
            <dt>Section 1</dt>
            <dd>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam.</dd>
            <dt>Section 2</dt>
            <dd>Vestibulum a velit eu ante scelerisque vulputate.</dd>
            <dt>Section 3</dt>
            <dd>Nam mi. Proin viverra leo ut odio. Curabitur malesuada.</dd>
            <dt>Section 4</dt>
            <dd>Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc.</dd>
        </dl>

 

5.撰寫jQuery的plugin

           (function($){
                $.fn.accordion=function(options){
                    var settings=$.extend({},{open:false},options);
                    return this.each(function(){
                        var dts=$(this).children('dt');
                        dts.click(onClick);
                        dts.each(reset);
                        if(settings.open){
                            $(this).children('dt:first-child').next().show();
                        }
                    });
                    
                    function onClick(){
                        $(this).siblings('dt').each(hide);
                        $(this).next().slideDown('fast');
                        return false;
                    }
                    
                    function hide(){
                        $(this).next().slideUp('fast');
                    }
                    
                    function reset(){
                        $(this).next().hide();
                    }
                    
                };
            })(jQuery);

 

6.plugin的用法

$('dl#my-accordion').accordion({open:true});

 

 

參考資料:http://www.ibm.com/developerworks/web/library/wa-jqplugin/

分類:jQuery