jquery高级应用—扩展插件方法

       为了顺利完成jquery插件的学习,细致阅读了jquery.grid 源码,感觉则个插件无论在效果显示,还是在使用方法上面,都非常方便。同时,给我们提供了封装jquery插件的良好思维。在此基础上,我借助jquery的另外一个插件jquery.datatables 封装了一个jquery.datatable.combox,来实现了输入框的下拉框选择功能。

     在此,简单总结了一下jquery插件封装的方法:

1、命名规则:

           a)插件的文件命名必须严格遵循jQuery.[插件名].js的规则,以便于与其他的js文件的区分,如新插件文件jquery.newplugin.js.
 
           b)如果是对象级别插件,所有的方法都应依附于jquery.fn主体对象;如果是类级别插件,所有的方法都应依附于jquery对象

2、demo,根据我写的插件,基本总结出了一个开发jquery插件的js框架,在这个基础上填充可以开发更强大的jquery插件。demo代码显示:

;(function($,window,undefined)
{
 $.combox = $.combox || {};
 $.extend($.combox,{
  version : "1.0.0",
  //访问方式:$.combox.testCombox();
  testCombox:function(){
   alert("testCombox");
  },
  
  extend : function(methods) {
   $.extend($.fn.combox,methods);
    if (!this.no_legacy_api) {
     $.fn.extend(methods);
    }
  }
 });
 /**
  * 对外开放的方法-访问方式:
  * combox = $('#adp-div').combox();
  * combox.getPWidth();
  */
 $.combox.extend({
  getPWidth:function(){
   var $t = this[0];
   alert($t.p.pWidth);
  }
 });
 
 
$.fn.combox=function(options)
 {   
  var _this = this;
  if($(_this)[0].tagName.toUpperCase()!="DIV"){
   alert("Element is not a div");
   return ;
  }
  //可以通过 option=width:'100px',height:'200px'}
  //var combox = $("#div_plugin").combox(option);设置参数
  var opts = $.extend(true,{},$.fn.combox.defaults,options);
  return this.each(function(){
    var p = $.extend(true,{
         pWidth:"100px",
      onSelectRow: null,   //选中行事件
      okBtnClick:null,  //确定按钮事件
     },options);
    var ts=this, combox={
      headers:[],
      footers: [],
      test:function(){
       alert(1111);
      }
    };
        
    //确定按钮事件
    if(p.okBtnClick){
     $(ts).find("#test_btn").live("click",function() {
      p.okBtnClick.call();
     });
    }
    //选中行事件
    if(p.onSelectRow){
     $(ts).find("#test_btn_tr").live('click',function(){
      p.onSelectRow.call($(this),$(this));
     });
    }
    
    ts.combox=combox; //装入 返回的对象中
    ts.p=p;    //装入 返回的对象中
  });
 };
 //默认设置
 $.fn.combox.defaults={
   width:'100px',
   height:'200px'
 };
})(jQuery,window);

jsp页面:

<script src="../jquery-1.8.3.js" type="text/javascript"></script>
<script src="jquery.newPlugin.js" type="text/javascript"></script>
<script language="javascript">
$(function(){
 $.combox.testCombox(); //alert :testCombox
    var option = {
      okBtnClick:function(){
        alert("点击确定按钮");
       },
      onSelectRow:function(){
        alert("您已经选中该行");
       }
     }
 var combox = $("#div_plugin").combox(option);
 combox.getPWidth(); //alert:100px
})

</script>
</head>
<body>
<div id="div_plugin" class="hilight { background: 'red', foreground: 'white' }">   
  Have a nice day!    <tr/>
  <input type="button" id="test_btn" value="确定" /><tr/>
  <input type="button" id="test_btn_tr" value="选中行" />
</div> 
</body>


 

你可能感兴趣的:(jquery高级应用—扩展插件方法)