如何制作只能在一组 div 中搜索特定元素的搜索过滤器?

目前,我可以通过键入大厅容器内的任何内容(包括名称、位置、容量)来搜索大厅,但是,我只想能够过滤大厅名称的搜索结果。

<div id="searchFilter" class="flexColumn">
      <label for="searchFilterText">Search for Community Halls</label>
      <input type="text" id="searchFilterText" placeholder="Search for the name of a community hall">
</div>

`<div class="hall">
      <div class="info">
          <p>${data.Halls[halls[i]].Location[0].Address},${data.Halls[halls[i]].Location[1].Suburb}<br>Capacity: ${data.Halls[halls[i]].Room[0]["Standing Capacity"]}</p> 
      </div>
      <div class="image">
          <img class="img" src="${data.Halls[halls[i]].Description[4].Photos}" alt="${data.Halls[halls[i]]["Hall Name"]}">
      </div>
      <div class="hallNameBox">
           <p class="hallName">${data.Halls[halls[i]]["Hall Name"]}</p>
      </div>
 </div>`;

$(document).ready(function(){
  $("#searchFilterText").on("keyup",function() {
    let value = $(this).val().toLowerCase();
    $(".hall").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
nuaadoudou 回答:如何制作只能在一组 div 中搜索特定元素的搜索过滤器?

不要使用 toggle,而是使用 showhide

(使用 onetwothree 来测试这个简化的示例)。

$(function() {
  $("#searchFilterText").on('keyup',function() {

    // Grab the value
    const value = $(this).val().toLowerCase();

    // If it's not empty
    if (value) {

      // `filter` all the hall elements if
      // the text of the hallName element doesn't start with
      // the value and hide them
      $('.hall').filter(function() {
        const text = $(this).find('.hallName').text().toLowerCase();
        return !text.startsWith(value);
      }).hide();

    // Otherwise show them
    } else {
      $('.hall').show();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="searchFilter" class="flexColumn">
<input type="text" id="searchFilterText" />
</div>

<div class="hall">
  <div class="hallNameBox">
    <p class="hallName">One</p>
  </div>
</div>
<div class="hall">
  <div class="hallNameBox">
    <p class="hallName">Two</p>
  </div>
</div>
<div class="hall">
  <div class="hallNameBox">
    <p class="hallName">Three</p>
  </div>
</div>

,
$(document).ready(function(){
  $("#searchFilterText").on("keyup",function() {
    let value = $(this).val().toLowerCase();
    $(".hall *").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});

这是你想要的吗?如果没有,请告诉我。

本文链接:https://www.f2er.com/6711.html

大家都在问