最近項目中用到了easyui這個框架,找了一圈也沒有找到checkbox list控件,被迫只能自己實現了,為了便於復用,自己封裝了下,有需要的,直接拿去用吧。有意見或建議的,歡迎指教啊。
調用示例
<html> <head> <title></title> <meta charset='utf8'> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript" src="jquery.checkbox.js"></script> </head> <body> <div class='easyui-checkbox' id='test'> </div> <div id='showValues'></div> <div> <input type='button' id='btnGetValue' value='獲取選中值'> </div> <script type="text/javascript"> $().ready(function function_name (argument) { //初始化傳值 /*$('#test').checkbox({data:[ {text:'星期天',value:'1'}, {text:'星期一',value:'2'}, {text:'星期二',value:'3'} ]});*/ //初始化 $('#test').checkbox(); //setValue設置checkbox項 $('#test').checkbox('setValue',[ {text:'星期天',value:'1'}, {text:'星期一',value:'2'}, {text:'星期二',value:'3'} ]); //checked設置默認選中項 $('#test').checkbox('checked',['2']); $('#btnGetValue').on('click',function(){ //getValue獲取已選擇的checkbox項的值 var checked=$('#test').checkbox('getValue'); $('#showValues').html(''); $('#showValues').html(checked.join(',')); }); }); </script> </body> </html>
實現源碼 jquery.checkbox.js
1 (function ($) { 2 function createBox(me, options) { 3 me.html(''); 4 5 if(options.data){ 6 $.each(options.data,function(index,item){ 7 me.append('<input type="checkbox" value="'+item.value+'"/>'+item.text); 8 }); 9 registerEvent(me); 10 } 11 } 12 13 function registerEvent(me){ 14 $(me).children().on('click',function(){ 15 if($(this).attr('checked')){ 16 $(this).removeAttr('checked'); 17 }else{ 18 $(this).attr('checked','checked'); 19 } 20 }); 21 } 22 23 $.fn.checkbox = function(options, param){ 24 if (typeof options == 'string'){ 25 var method = $.fn.checkbox.methods[options]; 26 27 if (method){ 28 return method(this, param); 29 } else { 30 return this.combo(options, param); 31 } 32 } 33 34 options = options || {}; 35 createBox(this,options); 36 }; 37 38 $.fn.checkbox.methods={ 39 setValue:function(me,para){ 40 me.html(''); 41 42 createBox(me,{data:para}); 43 }, 44 getValue:function(me,para){ 45 var values=new Array(); 46 47 $(me).children().each(function(index,item){ 48 if($(item).attr('checked')=='checked'){ 49 values.push($(item).attr('value')); 50 } 51 }); 52 53 return values; 54 }, 55 checked:function(me,para){ 56 $(me).children().each(function(index,item){ 57 if (para.indexOf($(item).attr('value')) > -1) { 58 if ($(item).attr('checked') != 'checked') { 59 $(item).click(); 60 } 61 } else { 62 $(item).removeAttr('checked'); 63 } 64 }); 65 } 66 }; 67 })(jQuery);