我如何使用 jquery 的搜索过滤器

我正在尝试创建一个列表组,该列表组将总结老师拥有的不同主题的列表。现在我想在搜索中搜索主题,但它不起作用。我如何使用此代码实现这一目标?


HTML + PHP 代码:


<div class="container">

    <h2>Filterable List</h2>

    <p>Type something in the input field to search the list for specific items:</p>

    <input class="form-control" id="myInput" type="text" placeholder="Search..">

    <br>

    <ul class="list-group" id="myList">

        <?php foreach ($data as $key => $val) { ?>

                <li class="list-group-item"><a>

                    <?php echo $val['name'] ?></a></li>

        <?php } ?>

    </ul>

</div>

jQuery 代码:


  $(document).ready(function() {

      $("#myInput").on("keyup", function() {

          var value = $(this).val().toLowerCase();

          $("#myList li a").filter(function() {

              $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)

          });

      });

  });

提前致谢!


12345678_0001
浏览 180回答 2
2回答

阿晨1998

使用此代码过滤您的搜索结果:我使用了一些示例数据:&nbsp; $('#myInput').keyup(function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var rex = new RegExp($(this).val(), 'i');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('.list-group .list-group-item').hide();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('.list-group .list-group-item').filter(function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return rex.test($(this).text());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).show();&nbsp; &nbsp; &nbsp; &nbsp; });<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="container">&nbsp; &nbsp; <h2>Filterable List</h2>&nbsp; &nbsp; <p>Type something in the input field to search the list for specific items:</p>&nbsp; &nbsp; <input class="form-control" id="myInput" type="text" placeholder="Search..">&nbsp; &nbsp; <br>&nbsp; &nbsp; <ul class="list-group" id="myList">&nbsp; &nbsp; &nbsp; &nbsp; <li class="list-group-item"><a>jan peters</a></li>&nbsp; &nbsp; &nbsp; &nbsp; <li class="list-group-item"><a>kees peters</a></li>&nbsp; &nbsp; &nbsp; &nbsp; <li class="list-group-item"><a>marcel test</a></li>&nbsp; &nbsp; &nbsp; &nbsp; <li class="list-group-item"><a>john doe</a></li>&nbsp; &nbsp; </ul></div>

江户川乱折腾

也许$(document).ready(function() {&nbsp; &nbsp; $("#myInput").on("keyup", function() {&nbsp; &nbsp; &nbsp; &nbsp; var value = $(this).val().toLowerCase();&nbsp; &nbsp; &nbsp; &nbsp; $("#myList li").filter(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $(this).text().toLowerCase.indexOf(value) > -1;&nbsp; &nbsp; &nbsp; &nbsp; }).toggle(true);&nbsp; &nbsp; &nbsp; &nbsp; $("#myList li").filter(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $(this).text().toLowerCase.indexOf(value) < 0;&nbsp; &nbsp; &nbsp; &nbsp; }).toggle(false);&nbsp; &nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP