我是新手,想问一下有关HTML列表过滤的问题。
我从
找到了这个脚本https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_filters_list
<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<div class="w3-container">
<h2>Filter List</h2>
<p>Search for a name in the input field.</p>
<input class="w3-input w3-border w3-padding" type="text" placeholder="Search for names.." id="myInput" onkeyup="myFunction()">
<ul class="w3-ul w3-margin-top" id="myUL">
<li>Adele</li>
<li>Agnes</li>
<li>Billy</li>
<li>Bob</li>
<li>Calvin</li>
<li>Christina</li>
<li>Cindy</li>
</ul>
</div>
<script>
function myFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
if (li[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>
</body>
</html>
如果找不到结果,我想添加“未找到数据”like this等消息。
怎么做? 谢谢。 抱歉我的英语不好。
答案 0 :(得分:0)
首先,您需要知道何时找不到数据。
在循环之前声明变量isFound = false
;每当你找到一条消息时都将其设置为true。
然后,您宣告内容为div
的{{1}},并在循环之后切换,就像您对其他列表项一样。
答案 1 :(得分:0)
添加单独的div
以显示结果未找到,默认情况下隐藏此元素。
创建一个单独的函数来显示找不到结果。而不是向li
添加内联样式,而是通过类hideElement
function myFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
if (li[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].classList.remove('hideElement');
} else {
li[i].classList.add('hideElement');
}
}
// Calling function to decide if no result div need to be shown or not
// passing the total `li` element.Ideally this should be total li
// which are child of ul in consideration
displayNoResult(li.length)
}
function displayNoResult(allLI) {
// get all the li which have hideElement as class
// if this is equal to the number of li that infers that all li are
// having hideElement class, which also infers that there is no matched
// result. In that case so the div for no result
var hiddenLILength = document.querySelectorAll('li.hideElement');
if (allLI === hiddenLILength.length) {
document.getElementById('noResult').classList.remove('hideElement')
} else {
document.getElementById('noResult').classList.add('hideElement')
}
}
.hideElement {
display: none;
}
<h2>Filter List</h2>
<p>Search for a name in the input field.</p>
<input class="w3-input w3-border w3-padding" type="text" placeholder="Search for names.." id="myInput" onkeyup="myFunction()">
<ul class="w3-ul w3-margin-top" id="myUL">
<li>Adele</li>
<li>Agnes</li>
<li>Billy</li>
<li>Bob</li>
<li>Calvin</li>
<li>Christina</li>
<li>Cindy</li>
</ul>
<div class="hideElement" id="noResult">
Result not found
</div>
</div>