如何使用jQuery访问内部html列表项 [英] How to access list items inner html using jQuery
问题描述
我有一个javascript片段接受文本输入,遍历ul> li,并根据内部html过滤项目。
I have a javascript snippet which accepts a text input, traverses through ul > li, and filters the items based on their inner html.
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";
}
}
现在我正在尝试将此代码段转换为jquery这样做但收到错误 html不是函数
:
Now I am trying to convert this snippet to jQUery and doing this but getting an error html is not a function
:
$('#inputSerachBox').on('keyup', function (e) {
var input, filter, ul, li, a, i;
input = $('#inputSerachBox');
filter = input.val().toUpperCase();
li = $('#ulWithItems li');
li.each(function (e) {
a = $('a', e)[0];
if (a.html().toUpperCase().indexOf(filter) > -1) {
console.log(a.html())
e.style.display = "";
} else {
e.style.display = "none";
}
})
})
我的选择器是错误的吗?
Are my selectors wrong?
推荐答案
S. ince,你需要第一个元素,所以你不能使用 [0]
因为它没有给你一个JQuery对象。相反,它会为您提供 HTML
元素,您无法在其中使用 html()
函数。
Since, you need the first element so you cannot use [0]
as it does not gives you a JQuery object. Instead, it gives you a HTML
element in which you cannot use html()
function.
你需要的是使用 eq()
或 get()
方法为,
What you need is to use either eq()
or get()
method as,
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";
}
})
OR
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";
}
})
这篇关于如何使用jQuery访问内部html列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!