2009-02-11 48 views

回答

10

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對象本身其實是做ne用於你的類需要但不擴展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