Пока l oop, чтобы скрыть элементы div - PullRequest
0 голосов
/ 24 апреля 2020

Я пытаюсь создать доступный для поиска контент с помощью некоторого 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();
    }

  });

};

Я понимаю, что какое-то время у l oop может быть условие, при котором, если userInput равен нулю, он будет l oop через каждое поле содержимого и скрыть элемент

Нечто подобное может быть?

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

Любая помощь будет принята с благодарностью.

Ответы [ 2 ]

1 голос
/ 24 апреля 2020

Вам потребуется обновлять переменную userInput каждый цикл l oop, потому что значение userInput никогда не обновляется. Тем не менее, это не очень хороший способ сделать это, потому что вы заблокируете все приложение.

Нет необходимости в oop, просто используйте оператор if. Кроме того, поскольку эта функция выполняется при изменении значения ввода, нет необходимости использовать это.

Вы можете поместить этот блок кода под $contentBoxes.each функцией:

$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();
}

  });



if (userInput === null) {
  $contentBoxes.each(function(){
      $(this).hide();
  });
}
0 голосов
/ 24 апреля 2020

Я думаю, что это будет работать так. Вы просто проверяете, введен ли поиск! == null, и не скрываете содержимое в этом случае

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