Quelle est la manière la plus simple de définir une nouvelle fonction membre jQuery?
Pour que je puisse appeler quelque chose comme:
$('#id').applyMyOwnFunc()
S’il vous plaît voir Définir vos propres fonctions dans jQuery :
Dans cet article, je souhaite vous présenter comment définir facilement vos propres fonctions dans jQuery et les utiliser.
De la poste:
jQuery.fn.yourfunctionname = function() { var o = $(this[0]) // It's your element return this; // This is needed so others can keep chaining off of this };
Utilisé:
$(element).yourfunctionname()
C’est ce modèle que je préfère définir mes propres plugins.
(function($) { $.fn.extend({ myfunc: function(options) { options = $.extend( {}, $.MyFunc.defaults, options ); this.each(function() { new $.MyFunc(this,options); }); return this; } }); // ctl is the element, options is the set of defaults + user options $.MyFunc = function( ctl, options ) { ...your function. }; // option defaults $.MyFunc.defaults = { ...hash of default settings... }; })(jQuery);
Appliqué comme:
$('selector').myfunc( { option: value } );
La documentation de jquery comporte une section sur la création de plug-ins, où j’ai trouvé cet exemple:
jQuery.fn.debug = function() { return this.each(function(){ alert(this); }); };
Vous pourrez alors l’appeler ainsi:
$("div p").debug();
jQuery a la fonction d’ extend
pour le faire
jQuery.fn.extend({ check: function() { return this.each(function() { this.checked = true; }); }, uncheck: function() { return this.each(function() { this.checked = false; }); } });
vous pouvez voir la documentation là
Voici un plugin, dans sa forme la plus simple …
jQuery.fn.myPlugin = function() { // do something here };
Vous voudrez vraiment consulter la documentation si:
/* This prototype example allows you to remove array from array */ Array.prototype.remove = function(x) { var i; for(i in this){ if(this[i].toSsortingng() == x.toSsortingng()){ this.splice(i,1) } } } ----> Now we can use it like this : var val=10; myarray.remove(val);