例如,我正在查看jCalendar源代码,创建者有两个不同的插件部分,一个函数在“jQuery.jcalendar”下,另一个函数在“jQuery.fn.jcalendar”下.两者分开的目的是什么?一个人做了什么呢?
解决方法
jQuery.fn.mypluging名称扩展了jQuery对象:
- $(selector); //a jquery object
- $(selector).myplugin();
jQuery.myplugin扩展了jquery对象本身:
- $; //the jQuery object
- $.myPlugin();
通过将您的插件添加到jQuery.fn,您可以对该选择器找到的对象执行操作:
- jQuery.fn.makeRed = function(){
- this.each( function() {
- $(this).css('color','red');
- }
- }
- $('div.someClass').makeRed(); //makes all divs of class someclass have red text
扩展jQuery对象本身是为了您的类需要但不扩展jQuery对象的函数.所以扩展我们前面的例子:
- jQuery.fn.doStuff = function(){
- this.each( function() {
- $(this).css('color','red')
- .append($.doStuff.giveMeRandom());
- }
- }
- jQuery.doStuff = {
- giveMeRandom: function() {
- return Math.random();
- }
- }
- $('div.someClass').doStuff(); //makes all divs of class someclass have red text and append a random number to them