2013-02-27 7 views
1

Я пытаюсь создать страницу, которая имитирует поиск в режиме реального времени. Результаты поиска отображаются как пользовательские типы. Плагин ниже работает хорошо, за исключением того, что я хочу скрыть результаты (упорядоченный список) в начале и показать каждый соответствующий маркер по типу пользователя.Поиск в режиме реального времени в jQuery

http://www.designchemical.com/blog/index.php/jquery/live-text-search-function-using-jquery/

JQuery

$(document).ready(function(){ 
$("#filter").keyup(function(){ 

    // Retrieve the input field text and reset the count to zero 
    var filter = $(this).val(), count = 0; 

    // Loop through the comment list 
    $(".commentlist li").each(function(){ 

     // If the list item does not contain the text phrase fade it out 
     if ($(this).text().search(new RegExp(filter, "i")) < 0) { 
      $(this).fadeOut(); 

     // Show the list item if the phrase matches and increase the count by 1 
     } else { 
      $(this).show(); 
      count++; 
     } 
    }); 

    // Update the count 
    var numberItems = count; 
    $("#filter-count").text("Number of Comments = "+count); 
}); 

});

HTML

<form id="live-search" action="" class="styled" method="post"> 
    <fieldset> 
     <input type="text" class="text-input" id="filter" value="" /> 
    </fieldset> 
</form> 

<ol class="commentlist"> 
    <li>Comment #1</li> 
    <li>Comment #2</li> 
</ol> 

Любая помощь приветствуется.

+0

Являются ли комментарии предварительно загруженными? –

ответ

7

Если комментарии предварительно загружены, вы можете скрыть их изначально двумя способами.

  1. вызова $ ('commentlist Ли'). Скрыть() на йот готовый

  2. Добавить стиль .commentlist li { display: none}

Другой незначительный щипок я хотел бы предложить создать регулярное выражение переменная вне оператора цикла

$(document).ready(function(){ 
    $("#filter").keyup(function(){ 

     // Retrieve the input field text and reset the count to zero 
     var filter = $(this).val(), count = 0; 
     if(!filter){ // hide is no text 
      $(".commentlist li").hide(); 
      return; 
     } 

     var regex = new RegExp(filter, "i"); // Create a regex variable outside the loop statement 

     // Loop through the comment list 
     $(".commentlist li").each(function(){ 

      // If the list item does not contain the text phrase fade it out 
      if ($(this).text().search(regex) < 0) { // use the variable here 
       $(this).hide(); 

      // Show the list item if the phrase matches and increase the count by 1 
      } else { 
       $(this).show(); 
       count++; 
      } 
     }); 

     // Update the count 
     var numberItems = count; 
     $("#filter-count").text("Number of Comments = " + count); 
    }); 
}); 

Демо: Fiddle

Вы можете, очевидно, использовать анимацию как fadeIn('slow') и fadeOut('slow') вместо show() и hide() для анимации отображения элементов, это на мой взгляд, это выглядит хорошо, как многие детали будут анимировать вместе.

+0

Спасибо за ответ. Дисплей: ни один стиль не работает, но когда текстовое поле очищено, я хочу снова скрыть комментарии. –

+0

Я получаю и ошибка при вводе в эту строку: var filter = $ (this).val(), count = 0, regex = новый RegExp (фильтр, «i»)); –

+0

, строка которого выдает ошибку –

2

В CSS добавить

.commentlist li{display:none;} 

Затем в JS, первый, если

if(filter == 0){$(this).fadeOut();} 

затем на последней, вместо $ (это) .show() добавить $ (это) .fadeIn ('медленный')

$(this).fadeIn('slow'); 

Ваш ОБНОВЛЕНО код здесь: http://tinyurl.com/a972s6t

+0

Спасибо за помощь. Это работает, но я хочу скрыть комментарии (li), когда текстовое поле очищается. –

0

Это должно сделать это для вас:

$(document).ready(function(){ 
    $('#filter').keyup(function() { 
     var f = $(this).val(); 
     var regex = new RegExp(f, 'gi'); 

     $('.commentlist li').hide() 
      .each(function() { 
       if($(this).html().match(regex)) { 
        $(this).show(); 
       } 
      }); 
    }); 
}); 

Если вы хотите исчезать анимации:

$(document).ready(function(){ 
    $('#filter').keyup(function() { 
     var f = $(this).val(); 
     var regex = new RegExp(f, 'gi'); 

     $('.commentlist li').fadeOut() 
      .each(function() { 
       if($(this).html().match(regex)) { 
        $(this).stop().show(); 
       } 
      }); 
    }); 
}); 

Демо скрипта в действии: http://www.glow-raspberry.com/where-to-buy. Например, введите «площадь».

Смежные вопросы