jQuery Passage de $ (this) à une fonction

J’ai des lignes de code comme ceci:

$(this).parent().parent().children().each(function(){ // do something }); 

Ça marche bien. Mais je dois exécuter ces lignes plusieurs fois. J’ai donc créé une fonction et transmis le paramètre $ (this) à une fonction:

 myFunc( $(this) ); function myFunc(thisObj) { thisObj.parent().parent().children().each(function(){ // do something }); } 

Mais de cette façon, cela n’a pas fonctionné.

vous pouvez vérifier ce lien.

http://jsfiddle.net/zEXrq/38/

 $("#f").click(function() { myFunc($(this)); }) function myFunc(thisObj) { thisObj.parent().parent().children().each(function() { alert("childs") }); } 
 
child

jQuery invoquera automatiquement votre fonction avec le jeu de contexte approprié.

 $('#button').on('click', myFunction); function myFunction() { var that = $(this); console.log(that); } 

Si vous travaillez en mode sans conflit (c’est-à-dire hors de scope mondiale), l’une des possibilités est la suivante:

 jQuery.noConflict(); (function ($) { $('#button').on('click', myFunction); }(jQuery)); // or jQuery('#button').on('click', myFunction); function myFunction() { var that = jQuery(this); console.log(that); }