Возьмите только 2 предмета из Jquery Loop - PullRequest
1 голос
/ 03 мая 2010

Вот мой Jquery

$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();
      }
      }
    }); 

Это часть функции типа tableFilter для таблицы HTML. Однако я хочу, чтобы он отображал только 2 результата. Я попытался создать какой-то счетчик индексов, но мне это не удалось. Любая помощь или мысли будут оценены.

Ответы [ 2 ]

1 голос
/ 03 мая 2010
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 голосов
/ 03 мая 2010

Это более эффективно, чем принятый ответ и не будет загрязнять ваше пространство имен.

(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));
...