我正在使用w3schools.com w3.js 搜索引擎
它工作正常,但是当搜索引擎无法与任何搜索匹配时,我需要它显示<div>
。
这是我的代码:
<input type="text" id="myInput" oninput="w3.filterHTML('#myTable', 'p', this.value)" placeholder="Search for names..">
<div id="myTable">
<div>
<p>Adele</p>
</div>
<div>
<p>Agnes</p>
</div>
<div>
<p>Billy</p>
</div>
<div>
<p>Bob</p>
</div>
</div>
<div id="no-data-div" style="display:none">
<p>No Results Found :(</p>
</div>
和脚本:
<script>
var w3 = {};
w3.getElements = function (id) {
if (typeof id == "object") {
return [id];
} else {
return document.querySelectorAll(id);
}
};
w3.filterHTML = function(id, sel, filter) {
var a, b, c, i, ii, iii, hit;
a = w3.getElements(id);
for (i = 0; i < a.length; i++) {
b = w3.getElements(sel);
for (ii = 0; ii < b.length; ii++) {
hit = 0;
if (b[ii].innerHTML.toUpperCase().indexOf(filter.toUpperCase()) > -1) {
hit = 1;
}
c = b[ii].getElementsByTagName("*");
for (iii = 0; iii < c.length; iii++) {
if (c[iii].innerHTML.toUpperCase().indexOf(filter.toUpperCase()) > -1) {
hit = 1;
}
}
if (hit == 1) {
b[ii].parentElement.style.display = "";
} else {
b[ii].parentElement.style.display = "none";
}
}
}
};
</script>
当隐藏所有其他div时,我希望“#no-data-div”可见。我怎样才能做到这一点?
答案 0 :(得分:0)
我花了一些时间调整你的代码。我相信这对你有用。我评论了你的代码,所以你知道每个部分正在做什么(据我所知),并根据需要进行调整......主要的补充只是通过脚本运行的计数器(totalHits ++),因此可以在结束以决定是否应显示无结果div。
w3.filterHTML = function(id, sel, filter) {
// w3 search filter function, adjusted by Nerdi.org (username on StackOverflow/my website)
// https://stackoverflow.com/questions/49742504/show-a-hidden-div-when-no-results-were-found-in-a-search-input
var a, b, c, i, ii, iii, hit;
a = w3.getElements(id);
// a.length will tell you # of tables (should be = to 1, as in 1 table being searched)
var totalHits = 0; // let's get a total count.
for (i = 0; i < a.length; i++) {
b = w3.getElements(sel);
// b.length will tell you # of valid selections (by tag, in this case you are searching the <p> tags)
for (ii = 0; ii < b.length; ii++) {
hit = 0;
if (b[ii].innerHTML.toUpperCase().indexOf(filter.toUpperCase()) > -1) {
hit = 1;
totalHits++;
}
c = b[ii].getElementsByTagName("*");
// c.length will tell us how many children this elem has so we can cycle through any child elements within the first selection (in this case, <p>)
var cLength = c.length;
for (iii = 0; iii < cLength; iii++) {
if (c[iii].innerHTML.toUpperCase().indexOf(filter.toUpperCase()) > -1) {
hit = 1;
totalHits++;
}
}
if (hit == 1) {
b[ii].parentElement.style.display = "";
} else {
b[ii].parentElement.style.display = "none";
}
}
}
// now that we've looped through all results, let's see if we found anything using our totalHits var that we set earlier :)
if(totalHits == 0){
document.getElementById('no-data-div').style.display = 'block'; // show the no results found
} else {
document.getElementById('no-data-div').style.display = 'none'; // hide the no results found
}
};