Fork me on GitHub

一个很简单的动态改变class插件

 1 ;(function($) {
 2 
 3 /**
 4 *    初始化插件
 5 *    @author: luofei
 6 *    @version: 2013/03/22
 7 *    @param:    {array}        options        初始化传入的json数据
 8 */
 9 
10 $.fn.lf = function(options){
11     this.opts = $.extend({}, $.fn.lf.defaults, options);
12     this._init();
13 };
14 
15 /*
16 *    插件的扩展函数    公共方法
17  */
18 $.fn.lf.prototype = {
19     _init: function() {
20 
21         var _this = this;    //获取当前对象
22         
23         //根据传入的参数确定选择器
24         var selector = _this.opts.id === "" ? "."+_this.opts.className : "#"+_this.opts.id;
25 
26         $(selector).each(function(index) {
27             $(this).bind(_this.opts.eventType,makeFunc(index,_this.opts));
28         });
29     }
30 }
31 
32 /*
33 *    内部私有方法    --闭包    
34 *    @param:    {int}    index    当前遍历的对象数组下标
35 *    @param:    {array}        opts    插件配置选项
36 * */
37 function makeFunc(index,opts){
38     return function(){
39         if(opts.id)
40             var item = $("#"+opts.id);
41         var item = $("."+opts.className);
42         for(var i=0; i<item.length; i++){
43             var attr = item[i].getAttribute("class");
44             if(i != index){
45                 attr = attr.replace(opts.toggleName,"");
46                 item[i].setAttribute("class",attr);
47             }
48             else{
49                 item[i].setAttribute("class",attr+" "+opts.toggleName);
50             }
51         }
52     };
53 }
54 
55 /*
56     * @param    {string}    id            选择器 id
57     * @param    {string}    className    选择器 class
58     * @param    {string}    toggleName    需增加的class
59     * @param    {string}    eventType    事件触发的类型
60 */
61 $.fn.lf.defaults = {
62     id: "",
63     className: "",
64     toggleName: "",
65     eventType: "click"
66 };
67 
68 })(jQuery);
69 
70 //应用实例
71 $(function(){
72     var lf = new $.fn.lf({
73         className: "item",
74         toggleName: "active"
75     });
76 });
posted @ 2013-03-22 12:04  Poised_flw  阅读(326)  评论(0)    收藏  举报