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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容