разрешить только 5 или менее результат за один раз, используя функцию jquery [duplicate]

0

Я нашел эту функцию, которая отображает результат в реальном времени. Я новичок в jquery, и я не знаю, как я могу отображать только 5 или менее живых результатов за раз. вот моя функция для вашей справки. Любая помощь будет оценена по достоинству.

$(window).load(function(){
    $(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){
            $(".commentlist li").hide();
            return;
        }

        var regex = new RegExp(filter, "i");
        // 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) {
                $(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);
    });
       });
    });
  • 1
    Пожалуйста, добавьте js-скрипку, чтобы играть с: jsfiddle.net
  • 1
    Также измените $(window).load(function(){ $(document).ready(function(){ на (function(){ и удалите последний});
Показать ещё 2 комментария
Теги:
jquery-plugins

5 ответов

2
Лучший ответ

Больше jQuery вроде бы:

    var count = $(".commentlist li").hide().filter(function() {
       return $(this).text().search(regex) >= 0; 
    }).slice(0,5).show().length;
  • 0
    Это остановится на первой итерации, так как возвращает что-то. Вы предпочитаете делать, if (index === 4) return;
  • 0
    @ojovirtual, спасибо должно быть !==
Показать ещё 6 комментариев
1

вы установили счетчик count переменной, просто проверьте ее, когда вы показываете результат:

$(".commentlist li").each(function(){

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

            // Show the list item if the phrase matches and increase the count by 1
            } else {
               if(count == 4)
               return false; 
                $(this).show();
                count++;
            }
        });
1
var count=0;
$(".commentlist li").each(function(){
    if (count == 5)
        return;
    // If the list item does not contain the text phrase fade it out
    if ($(this).text().search(regex) < 0) {
        $(this).hide();
    // Show the list item if the phrase matches and increase the count by 1
    } else {
        $(this).show();
        count++;
    }
});
  • 0
    Спасибо за ваш ответ. Это работает, когда вы набираете любое слово, но если вы удаляете символы один за другим, оно все равно отображает более 5 результатов ??
  • 0
    Попробуйте изменить if(!filter){ $(".commentlist li").hide();return;} на $(".commentlist li").hide(); ,
Показать ещё 1 комментарий
0
var items = $(".commentlist li");
    for( var i=0; i < items.length; i++){

        // If the list item does not contain the text phrase fade it out
        if (items.eq(i).text().search(regex) < 0) {
            items.eq(i).hide();

        // Show the list item if the phrase matches and increase the count by 1
        } else {
            items.eq(i).show();
            count++;
        }
        if(count == 5){
            break;
        }
    });
0

Добавьте это прямо перед концом каждого цикла:

return ( count !== 5 );

Ещё вопросы

Сообщество Overcoder
Наверх
Меню