gpt4 book ai didi

javascript - While循环隐藏div元素

转载 作者:行者123 更新时间:2023-12-02 20:59:00 26 4
gpt4 key购买 nike

我正在尝试在一些 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();
}
}

任何帮助将不胜感激。

最佳答案

您需要在循环的每个周期更新您的 userInput 变量,因为 userInput 值永远不会更新。尽管如此,这不是一个好方法,因为您将阻止整个应用程序。

不需要循环,只需使用 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();
});
}

关于javascript - While循环隐藏div元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61400501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com