Javascript 如何使用jQuery访问html内部的列表项
我有一个javascript片段,它接受文本输入,遍历ul>li,并根据项目的内部html过滤项目Javascript 如何使用jQuery访问html内部的列表项,javascript,jquery,html,Javascript,Jquery,Html,我有一个javascript片段,它接受文本输入,遍历ul>li,并根据项目的内部html过滤项目 var input, filter, ul, li, a, i; input = document.getElementById('inputSerachBox'); filter = input.value.toUpperCase(); ul = document.getElementById("ulWithItems"); li
var input, filter, ul, li, a, i;
input = document.getElementById('inputSerachBox');
filter = input.value.toUpperCase();
ul = document.getElementById("ulWithItems");
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";
}
}
我的选择器错了吗?表达式
$('a',e)[0]
生成一个本机DOM对象,而不是jQuery对象,因此它没有html()
函数。请尝试使用$('a',e).first()
因为您需要第一个元素,所以无法使用[0]
,因为它没有提供JQuery对象。相反,它提供了一个HTML
元素,您不能在其中使用HTML()
函数
您需要使用eq()
或get()
方法作为
li.each(function (e) {
a = $('a', e).eq(0);
if (a.html().toUpperCase().indexOf(filter) > -1) {
console.log(a.html())
e.style.display = "";
} else {
e.style.display = "none";
}
})
或
li.each(function (e) {
a = $('a', e).first();
if (a.html().toUpperCase().indexOf(filter) > -1) {
console.log(a.html())
e.style.display = "";
} else {
e.style.display = "none";
}
})
$('a',e)[0]代码>不返回JQuery元素。更改a=$('a',e)[0]代码>到a=$($('a',e)[0])代码>试试a=$('a',e).eq(0)
li.each(function (e) {
a = $('a', e).first();
if (a.html().toUpperCase().indexOf(filter) > -1) {
console.log(a.html())
e.style.display = "";
} else {
e.style.display = "none";
}
})