同时循环隐藏div元素

问题描述 投票:0回答:1

我试图在某些JS的帮助下创建可搜索的内容,但是当搜索字段中没有输入时,无法隐藏内容。

这是我的剧本:

var $searchContainer = $("#search");
var $contentBoxes = $searchContainer.find(".content");
var $searchInput = $searchContainer.find("#search-input");
var $searchBtn = $searchContainer.find("#search-btn");

$searchBtn.on("click", searchContent);
$searchInput.on("input", searchContent);

while($searchInput == null) {
    for($contentBoxes) {
        hide();
    }
}

function searchContent(){
    var userInput;

  //Check if call comes from button or input change
    if($(this).is(":button")){
    userInput = $(this).siblings("input").val();
  } else {
    userInput = $(this).val();
  }

  //make the input all lower case to make it compatible for searching
  userInput = userInput.toLowerCase();

  //Loop through all the content to find matches to the user input
  $contentBoxes.each(function(){

    var headerText = $(this).find(".title").text();
    var contentText = $(this).find(".description").text();
    //add the title and content of the contentbox to the searchable content, and make it lower case
    var searchableContent = headerText + " " + contentText;
        searchableContent = searchableContent.toLowerCase();


    //hide content that doesn't match the user input


    if(!searchableContent.includes(userInput)){
      $(this).hide();
    } else {
      $(this).show();
    }

  });

};

我知道while循环可能有一个条件,如果userInput等于null,它将循环遍历每个内容框并隐藏该元素。

也许是这样?

while($searchInput == null) {
    $contentBoxes.each(function(){
        hide();
    }
}

任何帮助将不胜感激。

javascript html web-site-project
1个回答
0
投票

我认为这样会起作用。您只需检查搜索输入是否为!== null,在这种情况下不隐藏任何内容

if($searchInput != null && !searchableContent.includes(userInput)){
    $(this).hide();
 } else {
    $(this).show();
 }
© www.soinside.com 2019 - 2024. All rights reserved.