所以我正在使用这个from w3schools的方法,但我想搜索整个<li>
而不仅仅是<a>
标签。我可以看到这是问题a = li[i].getElementsByTagName("a")[0];
,但我无法弄清楚如何改变它?
这是他们的标记:
<ul id="myUL">
<li><a href="#">Adele</a></li>
<li><a href="#">Agnes</a></li>
</ul>
但我想要这个:
<input type="text" id="myInput" onkeyup="myFunction()"
placeholder="Search for names..">
<ul id="myUL">
<li><a href="#">Adele</a> - Some more text that gets picked up by
search.</li>
<li><a href="#">Agnes</a> - Some more text that gets picked up by
search.</li>
</ul>
这是剧本:
<script>
function myFunction() {
// Declare variables
var input, filter, ul, li, a, i;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName('li');
// Loop through all list items, and hide those who don't match the
search query
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>
答案 0 :(得分:2)
您只需通过以下
替换indexof行中的a标记if (li[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
你可以看看这里的工作示例,但我没有改变任何样式,我只是在搜索的地方改变了
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++) {
a = li[i].getElementsByTagName("a")[0];
if (li[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
&#13;
* {
box-sizing: border-box;
}
#myInput {
background-image: url('/css/searchicon.png');
background-position: 10px 12px;
background-repeat: no-repeat;
width: 100%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;
}
#myUL {
list-style-type: none;
padding: 0;
margin: 0;
}
#myUL li a {
border: 1px solid #ddd;
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6;
padding: 12px;
text-decoration: none;
font-size: 18px;
color: black;
display: block
}
#myUL li a.header {
background-color: #e2e2e2;
cursor: default;
}
#myUL li a:hover:not(.header) {
background-color: #eee;
}
&#13;
<h2>My Phonebook</h2>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<ul id="myUL">
<li><a href="#" class="header">A</a></li>
<li><a href="#">Adele</a>some other funcky text</li>
<li><a href="#">Agnes</a></li>
<li><a href="#" class="header">B</a></li>
<li><a href="#">Billy</a></li>
<li><a href="#">Bob</a></li>
<li><a href="#" class="header">C</a></li>
<li><a href="#">Calvin</a></li>
<li><a href="#">Christina</a></li>
<li><a href="#">Cindy</a></li>
</ul>
&#13;