【问题标题】:Searching page content with a partial string from a HTML input value使用 HTML 输入值中的部分字符串搜索页面内容
【发布时间】:2016-07-14 16:16:58
【问题描述】:

所以我正在尝试在页面上实现基本的搜索功能。我有一个由多个<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>

当您在搜索栏中输入时,任何不包含当前值的&lt;h4&gt; 都将从页面中删除。到目前为止,这是我的代码,但我找不到让部分搜索匹配发生的方法,只有完全匹配。

例如,如果您搜索 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();
            }
        });
    });
});

【问题讨论】:

  • indexof 是正确的工具,但直接的问题是您在元素上调用它而不是元素的文本,它适用于字符串

标签: javascript jquery html indexof


【解决方案1】:

您可以使用 .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>

【讨论】:

    【解决方案2】:

    考虑区分大小写:

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

    【讨论】:

      猜你喜欢
      • 2018-08-06
      • 2018-11-15
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 2018-01-05
      相关资源
      最近更新 更多