jQuery編寫插件基礎篇(選項卡)

jQery的插件對于jQuery的功能方法具有很好的擴展性,對于初次編寫插件的同學,總會有點二丈和尚摸不著頭腦,今天樓主就用一個選項卡的小例子,來描述下寫插件的過程與注意事項

第一步引入jquery和編寫相關的css屬性

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>選項卡</title>
<script src="js/jquery-1.12.3.min.js" ></script>
<style>
 body,h1,h2,h3,h4,h5,h6,p,dl,dd,ul,ol,pre,form,input,textarea,th,td,select{margin:0; padding:0;}
    em{ font-style:normal;}
    li{list-style:none;}
    a{text-decoration:none;}
    img{border:none;vertical-align:top;}
    table{border-collapse;}
    textarea{ resize:none; overflow:auto;} 
    #div1 div{width:200px;height:200px;border: 1px solid #000;display: none;}
    #div1 .active{background: red;}
</style>
</head>
<body>
<div id="div1">
 
</div>
</body>
</html>

第二步編寫插件

<script>
    (function($){
          $.fn.extend({
              tab : fnTab        //在對象的原型上添加tab的方法
           });
 var defaults={
            header:['1','2','3'],
            bodys:['1111','2222','3333'],     //不加參數時,選項卡的默認樣式
            events:'click'
        }
        var setThings={};
        var $parent=null;
        function fnTab(options){
           $.extend(setThings,defaults,options);     //理解$.extend()對象拷貝的原理
               $parent=this;
               create();
               bind();
        }
        function bind(){
          //實現選項卡的功能
          $('input').on(setThings.events,function(){              $('input').eq($(this).index()).attr('class','active').siblings().attr('class','');
              $('#div1 div').eq($(this).index()).show().siblings('#div1 div').hide();
          })   
        }
        function create(){
             //創建元素到父級里面
             $.each(setThings.header,function(i,val){    
                    var $input=$('<input type="button" value="'+val+'">');                
                  $parent.append($input);
                  if(i==0){       
                   $input.attr('class','active');
                  }     
             });
             $.each(setThings.bodys,function(i,val){
                var $oDiv=$('<div>'+val+'</div>');
                $parent.append($oDiv);
                if(i==0){
                  $oDiv.show();
                }
              }) 
        }
})(jQuery)
</script>

第三步調用插件

<script type="text/javascript">
 $(function(){
  $('#div1').tab({
    header:["教育","工作","新聞","體育"],
    bodys:['lalalala','tytututtut','dhfgdhghfgg','ajdywayg'],
    events:'mouseover'   
  });   //參數可以改變選項卡的默認樣式
 })
</script>

效果地址 :http://www.sunyimin.cn/17jq.html

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容