gpt4 book ai didi

javascript - Jquery - 隐藏 div 的文本过滤器

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:52:39 24 4
gpt4 key购买 nike

我正在尝试使用 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>

我希望它能工作,以便只要有人输入“o”,苹果 div 就会隐藏,但目前它会在输入任何内容后立即隐藏所有 div。

还有如何让它不区分大小写?

最佳答案

非常感谢所有回答这个问题的人——最后我选择了 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();
}
});
});

关于javascript - Jquery - 隐藏 div 的文本过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22785209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com