[英]Search/ filter function javascript does not work
我想修改我在 W3school 上看到的代碼,代碼是生成過濾器/搜索 function。 原始代碼是
<script>
function myFunction() {
// Declare variables
var input, filter, ul, li, a, i, txtValue;
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];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>
下面的代碼旨在將輸入與錨元素的 data-caption 屬性進行比較,但它不起作用。 誰能指出什么是錯的? 非常感謝!
function search() {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById('search-input');
filter = input.value.toUpperCase();
ul = document.getElementById('search-opt');
li = ul.getElementsByTagName('li');
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0].getAttribute('data-caption');
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
嘗試刪除.getAttribute('data-caption')
,也許它會有所幫助,因為 W3Schools 不在他們的代碼中使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.