簡體   English   中英

如果使用 JavaScript 未找到結果,如何顯示“未找到結果”警報消息?

[英]How to show "No result found" alert message if no result found using JavaScript?

如果未找到用戶查詢,如何顯示警報消息。 當用戶在搜索欄中鍵入“asdfdsas”之類的內容時,用戶應該收到“未找到結果”之類的警報。 有什么辦法可以使用javascript來實現嗎?

 function myFunction() { var input, filter, ul, li, a, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); ul = document.getElementById("myUL"); li = ul.getElementsByTagName("li"); for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; txtValue = a.textContent || a.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].style.display = "none"; } } }
 <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name"> <ul id="myUL"> <li><a href="#">Adele</a></li> <li><a href="#">Agnes</a></li> <li><a href="#">Billy</a></li> <li><a href="#">Bob</a></li> <li><a href="#">Calvin</a></li> <li><a href="#">Christina</a></li> <li><a href="#">Cindy</a></li> </ul>

不確定您是否想要警報(警報可能很煩人)或消息。

如果你想要一個消息。

這是一個解決方案,並注意評論:

 function myFunction() { var input, filter, ul, li, a, i, txtValue, noResult; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); ul = document.getElementById("myUL"); li = ul.getElementsByTagName("li"); // no-result-found element noResult = document.querySelector('p'); // determine if any result is found, false by default let found = false; for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; txtValue = a.textContent || a.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; // set found to true found = true; } else { li[i].style.display = "none"; } } // if no results are found, show no-result-found element, and vice versa if(found) { noResult.style.display = 'none'; } else { noResult.style.display = ''; // if you want an alert instead, uncomment the next line and remove the previous line // alert('No result found'); } }
 <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name"> <ul id="myUL"> <li><a href="#">Adele</a></li> <li><a href="#">Agnes</a></li> <li><a href="#">Billy</a></li> <li><a href="#">Bob</a></li> <li><a href="#">Calvin</a></li> <li><a href="#">Christina</a></li> <li><a href="#">Cindy</a></li> </ul> <!-- Make an element for showing no result, hidden by default --> <p style="display: none;">No result found</p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM