使用来自 HTML 输入值的部分字符串搜索页面内容

Searching page content with a partial string from a HTML input value

所以我正在尝试在页面上实现基本的搜索功能。我有一个由多个 <div> 和一个搜索栏 <input> 构成的页面,如下所示:

<input id="search" type="text">

<div class="panel-flex">
    <h4>Title One</h4>
</div>
<div class="panel-flex">
    <h4>Title Two</h4>
</div>
<div class="panel-flex">
    <h4>Title Three</h4>
</div>

当您在搜索栏中输入内容时,任何不包含当前值的 <h4> 都将从页面中删除。到目前为止,这是我的代码,但我找不到进行部分搜索匹配的方法,只能进行完全匹配。

例如,如果您搜索 t,那么所有内容都会显示,但如果您搜索 th,则只会显示 Title Three

$(document).ready(function() {
    $("#search").on("keyup", function() {
        var searchTerm = $(this).val();
        $(".panel-flex").each(function() {
            $(this).hide();
            if ($(this).find("h4").text() == searchTerm) {
                $(this).show();
            }
        });
    });
});

我想要像 PHP 的 strpos() 函数一样工作的东西,所有调查都让我找到了 JavaScript 函数 indexOf(),但我试图在我的代码破坏得更多。

$(document).ready(function() {
    $("#search").on("keyup", function() {
        var searchTerm = $(this).val();
        $(".panel-flex").each(function() {
            $(this).hide();
            if ($(this).find("h4").indexOf(searchTerm) != -1) {
                $(this).show();
            }
        });
    });
});

考虑区分大小写:

searchTerm = searchTerm.toLowerCase();
$(".panel-flex").each(function() {
    if ($(this).find("h4").text().toLowerCase().indexOf(searchTerm) == -1) {
        $(this).hide();
    } else {
        $(this).show();
    }
});

您可以使用 .filter();

$(document).ready(function() {
    $("#search").on("keyup", function() {
        $('.panel-flex').hide();
        var searchTerm = $(this).val().toLowerCase();
         $('.panel-flex').filter(function(){
              return  $(this).find("h4").text().toLowerCase().indexOf(searchTerm) > -1;
        }).show();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" type="text">

<div class="panel-flex">
    <h4>Title One</h4>
</div>
<div class="panel-flex">
    <h4>Title Two</h4>
</div>
<div class="panel-flex">
    <h4>Title Three</h4>
</div>