[英]How can I hide my HTML table, when a search is finished?
我試圖讓我的HTML表加載隱藏,它只顯示與用戶搜索相匹配的“匹配”,並且每當搜索沒有發生時,該表應該返回隱藏狀態。
<html>
<table id="dvExcel"></table>
</html>
<style>
#dvExcel{
display: none;
}
</style>
<script>
function myFunction() {
//this is the search function
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
and store
table = document.getElementById("dvExcel");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td ) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
table.style.display = "block";
tr[i].style.display = "";
}else {
tr[i].style.display = "none";
}
}
}
}
</script>
我的HTML表加載隱藏,每次我搜索它都顯示命中,但當我刪除搜索框中的文本時,表不會再回到隱藏狀態。 相反,它顯示整個表格。
您將表設置為阻止但從未將其設置為無。 使用現有的for循環,添加一個檢查以查看是否找到任何匹配。 如果沒有找到則隱藏整個表,而不僅僅是行。
var foundHit = false; // Add this
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td ) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
table.style.display = "block";
tr[i].style.display = "";
foundHit = true; // Add this
}else {
tr[i].style.display = "none";
}
}
}
if (!foundHit) table.style.display = "none"; // Add this
當找不到任何內容時,您忘記將表的顯示樣式設置為none:
table.style.display = "none";
這是完整的工作代碼:
var theButton = document.getElementById("b1"); theButton.onclick = myFunction1; theButton = document.getElementById("b2"); theButton.onclick = myFunction2; function myFunction1() { myFunction ('something'); } function myFunction2() { myFunction (); } function myFunction (myInput) { var table = document.getElementById("dvExcel"); var tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td ) { if (myInput) { table.style.display = "block"; tr[i].style.display = ""; } else { table.style.display = "none"; tr[i].style.display = "none"; } } } }
#dvExcel { display: none; }
<h3> table show/hide test </h3> <table id="dvExcel"><tr><td>This is the table. It is visible now.</td></tr></table> <button id="b1"> find something </button> <button id="b2"> don't find anything </button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.