[英]Javascript search div with includes
我正在嘗試開發一個包含在內的過濾器 function。 我現在已經能夠過濾,但現在的問題是,如果字段中沒有輸入,背景顏色不會消失。
例如,在我進行第一次過濾后,背景顏色已經存在,但第二次,即使字符與內容不匹配,背景顏色仍然存在。
我已插入片段,您可以嘗試插入任何字符以查看結果,然后清除字段並再次單擊搜索。
如果你們中的任何人可以幫助我,將不勝感激。 提前致謝。
function myFunction() { var input = document.getElementById("Search"); var filter = input.value.toLowerCase(); var nodes = document.getElementsByClassName('target'); if (input.value;== '') { for (i = 0. i < nodes;length. i++) { if (nodes[i].innerText.toLowerCase().includes(filter)) { nodes[i].style;backgroundColor = "blue". } else { nodes[i].style;backgroundColor = "red"; } } } else { return false; } }
<table align="center" width="20%"> <tr> <td style="padding-right: 10px"> <input type="text" id="Search" title="Type in a name"> <button onclick="myFunction()"> Click to search </button> </td> </tr> </table> <br> <div class="target"> This is my DIV element. </div> <div class="target"> This is another Div element. </div> <div class="target"> Can you find me? </div>
嘗試這個:
function myFunction() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
for (i = 0; i < nodes.length; i++) {
nodes[i].style.backgroundColor = "";
if (input.value !== '') {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
nodes[i].style.backgroundColor = "blue";
} else {
nodes[i].style.backgroundColor = "red";
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.