JQ插件

一直不知道如何写插件,现在因为工作的需求,必须要了解到更多。于是了解了关于插件的一些知识。

总的来讲,插件就是一种程序写法,是为了更好的扩展。

Query插件的开发包括两种:

1、类级别的插件开发

1.1 添加一个新的全局函数

添加一个全局函数,我们只需如下定义:

jQuery.foo = function() { 
    alert('This is a test. This is only a test.');
};  

 1.2 增加多个全局函数

jQuery.foo = function() { 
    alert('This is a test. This is only a test.');
};
jQuery.bar = function(param) { 
    alert('This function takes a parameter, which is "' + param + '".');
}; 
//调用时和一个函数的一样的:jQuery.foo();jQuery.bar();或者$.foo();$.bar('bar');

//也可以这样。
var aa={};
aa.foo = function() { 
	alert('This is a test. This is only a test.');
};
aa.bar = function(param) { 
	alert('This function takes a parameter, which is "' + param + '".');
}; 
aa.foo();

 1.3 使用jQuery.extend(object);

jQuery.extend({    
    foo: function() {    
        alert('This is a test. This is only a test.');    
    },    
    bar: function(param) {    
        alert('This function takes a parameter, which is "' + param +'".');    
    }   
});
            

 1.4 使用命名空间

jQuery.myPlugin = {        
    foo:function() {        
        alert('This is a test. This is only a test.');        
    },        
    bar:function(param) {        
        alert('This function takes a parameter, which is "' + param + '".');  
    }       
};
//采用命名空间的函数仍然是全局函数,调用时采用的方法:
$.myPlugin.foo();       
$.myPlugin.bar('baz');
        

 2、对象级别的插件开发

对象级别的插件开发需要如下的两种形式:

形式1:

(function($){   
$.fn.extend({   
    pluginName:function(opt,callback){   
          // Our plugin implementation code goes here.     
    }   
})   
})(jQuery);   

 形式2:

(function($) {     
$.fn.pluginName = function() {   
     // Our plugin implementation code goes here.   
};   
})(jQuery);    

 暂时理解这些,后续再补上。