2012-01-07 5 views
1

Je veux écrire une fonction pour que je puisse exécuter des commandes comme ceci:Écrire votre propre fonction Jquery?

$("#Button").glow(); 

Qu'est-ce que je dois passer outre, ou comment dois-je structurer la fonction « lueur » afin que je puisse appeler la comme je fais ci-dessus?

+2

lire le (http [Documentation]: // docs .jquery.com/Plugins/Authoring) –

Répondre

9

Jetez un oeil à plugin authoring. Lisez la documentation. Faites et essayez quelque chose. Comme par exemple:

(function($) { 
    $.fn.glow = function(options) { 
     return this.each(function() {  
      // TODO: do something for each element that matched your selector 
     }); 
    }; 
})(jQuery); 
+4

-1 pour l'attitude –

7
(function($) { 
    $.fn.glow = function() { 
     return this.each(function() { //<--optionally, parameters here 
      // your logic here 
      // `this` at this point refers to the DOM element 
     }); 
    } 
})(jQuery); //<-- Closure to allow using $ where $ is not jQuery any more 

return dans return this.each(..) permet enchaînant les plugins jQuery, de sorte que vous pouvez utiliser:

$("selector").glow().anothermethod(); 
//If return was omitted, the previous line would throw an error 
1
jQuery.fn.glow = function() { 
    //Do Stuff 
} 
2
(function($){ 

    $.fn.glow = function() { 

    //your selected element is 'this' 
    this. ...//do your magic 

    }; 
})(jQuery); 

Et vous pouvez alors l'utiliser comme ceci:

$('#element').glow(); 

Pour des informations complètes, vérifiez est: http://docs.jquery.com/Plugins/Authoring

9

Vous devez déclarer une fonction jQuery comme comme:

jQuery.fn.myPlugin = function() { 

    // Do your awesome plugin stuff here 

}; 

et après que

$("#Button").myPlugin(); 

lire ici http://docs.jquery.com/Plugins/Authoring

Questions connexes