Jquery - 隐藏div的文本过滤器

Ray*_*Zor 3 javascript css jquery

我正在尝试使用jquery来创建一个实时过滤器来隐藏实时文本输入上的div.到目前为止,我有以下内容:

<input type="text" class="form-control" id="filter" name="filter" class="filter">
<div class="media">
    <div class="media-body>
        <h4>Apples</h4>
        ...
    </div>
</div>
<div class="media">
    <div class="media-body>
        <h4>Oranges</h4>
        ...
    </div>
</div>

<script>
    $('#filter').keyup(function () { 
        var filter = $("#filter").val();
        $('.media').each(function(i, obj) {
            if ($('this > .media-body > h4:contains(filter)').length === 0) {
                $(this).css("display","none");
            }
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

我希望这个工作,以便只要有人输入'o',就会隐藏苹果div,但目前只要输入任何内容就会隐藏所有div.

另外,我怎样才能使它不区分大小写?

Ray*_*Zor 7

非常感谢回答这个问题的所有人 - 最后我选择了Fabrizio Calderan提供的解决方案,但对其进行了一些修改,允许文本过滤器以任意顺序搜索字符串中的单词并重新显示以前隐藏的内容div如果用户删除了他们输入的内容,我想我会与你分享这个修改后的解决方案:

    $('#filter').keyup(function () {
        var filter_array = new Array();
        var filter = this.value.toLowerCase();  // no need to call jQuery here

        filter_array = filter.split(' '); // split the user input at the spaces

        var arrayLength = filter_array.length; // Get the length of the filter array

        $('.media').each(function() {
            /* cache a reference to the current .media (you're using it twice) */
            var _this = $(this);
            var title = _this.find('h4').text().toLowerCase();

            /* 
                title and filter are normalized in lowerCase letters
                for a case insensitive search
             */

            var hidden = 0; // Set a flag to see if a div was hidden

            // Loop through all the words in the array and hide the div if found
            for (var i = 0; i < arrayLength; i++) {
                 if (title.indexOf(filter_array[i]) < 0) {
                    _this.hide();
                    hidden = 1;
                }
            }
            // If the flag hasn't been tripped show the div
            if (hidden == 0)  {
               _this.show();
            }
        });
    });
Run Code Online (Sandbox Code Playgroud)


fca*_*ran 6

您需要使用实际值正确插值选择器字符串filter.
你也有一个错字$('this > ....

试试这段代码(有一些改进)

$('#filter').keyup(function () {

    var filter = this.value.toLowerCase();  // no need to call jQuery here

    $('.media').each(function() {
        /* cache a reference to the current .media (you're using it twice) */
        var _this = $(this);
        var title = _this.find('h4').text().toLowerCase();

        /* 
            title and filter are normalized in lowerCase letters
            for a case insensitive search
         */
        if (title.indexOf(filter) < 0) {
            _this.hide();
        }
    });
});
Run Code Online (Sandbox Code Playgroud)