首页 > 解决方案 > 引导程序 4,列表组,搜索所有但显示有限行

问题描述

我有一个脚本,它将数据库行显示为带有搜索栏的列表组。是的,它有效。

但是数据库有大约 10.000 行。我只想显示列表组中的前 5 行,但我想用于搜索所有行。

    <ul class="list-group" id="myList">
   <?
      if ($result = $conn->query($sql)) {
      
      /* fetch object array */
      while ($row = $result->fetch_row()) {
      if ($show_row < 6) echo "<li class='list-group-item'>$row[0]</li>"; // show row
      if ($show_row > 5) echo "<li class='list-group-item'>$row[0]</li>"; // hide row, but use it for search
          $show_row++;
      }
      }
      ?>
</ul>

<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myList li").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>  

感谢您的回答;-)

标签: phpbootstrap-4listgrid

解决方案


display:none最简单的方法是在最初不想显示的行上使用 CSS ,然后在没有输入的情况下重置为原始状态。我还将预先消化可搜索的值并将它们作为数据属性插入li标签中,这样您就不必在搜索期间为每个项目实时计算。

<ul class="list-group" id="myList">
    <?php
    if ($result = $conn->query($sql))
    {
        /* fetch object array */
        $i = 0;
        while ($row = $result->fetch_row())
        {
            /*
                Pre-digest the searchable string so we don't have to do this in JS for every comparison
                Set this as a data attribute in the li tag
                If you need something more than just strtolower, think about encapsulating this in a function.
            */
            $currSearchableValue = strtolower($row[0]);

            /*
             * Set any rows after the first 5 to display: none
             * Alternatively, you could just insert them all into the page displayed, then use JS to hide the rows,
             * but the user would see the list briefly, and the page contents would jump, which is amateur hour stuff.
             */
            $currStyleAttr = ($i>=5) ? ' style="display: none"':'';

            echo '<li class="list-group-item" data-searchable="'.$currSearchableValue.'"'.$currStyleAttr.'>'.$row[0].'</li>';
            $i++;
        }
    }
    ?>
</ul>

<script>
    $(document).ready(function ()
    {
        var $listItems = $("#myList li");
        $("#myInput").on("keyup", function ()
        {
            var value = $(this).val().toLowerCase();

            // Only search if we have input, otherwise reset the list
            if(value.length>0)
            {
                $listItems.filter(function()
                {
                    $(this).toggle($(this).data("searchable").indexOf(value) > -1)
                });
            }
            else
            {
                $listItems.hide().slice(0, 5).show();
            }
        });
    });
</script>

推荐阅读