gpt4 book ai didi

JavaScript ||通过 UL 过滤

转载 作者:行者123 更新时间:2023-12-01 02:14:25 25 4
gpt4 key购买 nike

我想构建一个搜索输入,过滤所有 UL 并隐藏不包含搜索词的元素。

目前,它检查 li 元素是否包含搜索词,但不会循环所有 li 元素来检查搜索词是否已命名。

例如,如果我现在有一个包含 3 个 li 的 ul。它只检查第一个,而不检查其余的,从而导致过滤系统无效。

Does anyone know how i can improve my code to make it filter all li elements and hide the parent ul if it doesn't contain the search word?

Javascript

function myFunction() {
// Declare variables
var input, filter, ul, li, a, i, div;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
div = document.getElementById("partners");
li = div.getElementsByTagName('li');

// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].parentElement.style.display = "";
} else {
li[i].parentElement.style.display = "none";

}
}
}

HTML/PHP

<div id="partners">
<?php echo "Count: " . count($partners)."<br>"; ?>
<?php foreach ($partners as $partner): ?>
<ul class="partner">
<li><b>contact name:</b><a href="#"><?php echo $partner['name'] ?></a></li>
<li><b>Company name:</b><a href="#"><?php echo $partner['companyname'] ?></a></li>
<li><b>Country:</b><a href="#"><?php echo $partner['country'] ?></a></li>
<li><b>Phonenumber:</b><a href="#"><?php echo $partner['number'] ?></a></li>
<li><b>Business:</b><a href="#"><?php echo $partner['business'] ?></a></li>
</ul>
<?php endforeach ?>
</div>

更改 PHP 使代码可以工作:

            <div id="partners"> 
<ul id="myUL">
<?php foreach ($partners as $partner): ?>
<li class="partner" id="">
<a id="a" href="#">
<b>Contact name:</b><h3><?php echo $partner['name'] ?></h3><br>
<b>Company name:</b><h3><?php echo $partner['companyname'] ?></h3><br>
<b>Country:</b><h3><?php echo $partner['country'] ?></h3><br>
<b>Phonenumber:</b><h3><?php echo $partner['number'] ?></h3><br>
<b>Business:</b><h4><?php echo $partner['business'] ?></h4><br>
</a>
</li>
<?php endforeach ?>
</ul>
</div>

最佳答案

即使其中一个 li 的文本不匹配,您也会隐藏 UL

使用querySelectorAllArray.fromfilter

var hasMatch = Array.from( document.querySelectorAll( "#partners ul li a") ).filter( function(el){
return el.textContent.toUpperCase().includes(filter);
}).length > 0

现在,如果 hasMatch 为 0,则隐藏 UL

if ( hasMatch == 0 )
{
document.querySelector( "#partners ul" ).style.display = "none";
}
else
{
document.querySelector( "#partners ul" ).style.display = "";
}

关于JavaScript ||通过 UL 过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49559328/

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