2010-05-03 7 views
1

Voici mon JqueryGrab seulement 2 articles de Jquery boucle

$th.each(function(idx) { 
     var notSelected = $(this).text(); 
     if ((notSelected.indexOf(to) != -1) || (notSelected.indexOf(from) != -1)) { 

     if (idx < 10) 
     { 
     $(this).show(); 
     // and show its corresponding td 
     $td.eq(idx).show(); 
     } 
     } 
    }); 

Il fait partie d'une fonction de type TableFilter pour une table HTML. Cependant, je veux qu'il affiche seulement 2 des résultats. J'ai essayé d'instancier une sorte de compteur d'index mais je n'ai pas réussi. Toute aide ou pensée serait appréciée.

Répondre

1
var index = 0; 
$th.each(function(idx) { 
     var notSelected = $(this).text(); 
     if ((notSelected.indexOf(to) != -1) || (notSelected.indexOf(from) != -1)) { 

     if (idx < 10 && index < 2) 
     { 
     $(this).show(); 
     // and show its corresponding td 
     $td.eq(idx).show(); 
     index = index + 1; 
     } 
     } 
    }); 
+0

ou vous pouvez utiliser index + = 1; comme cette dernière ligne dans le bloc interne if. –

0

Ceci est plus efficace que la réponse acceptée et ne pollue pas votre espace de noms.

(function(index){ 
    $th.each(function(idx) { 
     if(idx < 10){ 
      var self = $(this), 
       notSelected = self.text(); 
      if (notSelected.indexOf(to) > -1 || notSelected.indexOf(from) > -1) 
       self.show(); 
       // and show its corresponding td 
       $td.eq(idx).show(); 
       if(++index===2){ 
        //break the loop 
        return false; 
       } 
      } 
     } 
    }); 
}(0)); 
Questions connexes