我的html
<input type="text" placeholder="Search Posts" class="filterPosts"/>
<ul class="postsList">
</ul>
我的Posts.json 但是我认为这是对的,因为我在这里什么都没做
{
"posts" : [
{
"name" : "Como fazer um SearchBox",
"url" : "https://google.com",
"description": "blablavlablablabla bla blablabla"
},
{
"name" : "Melhores apps para programar",
"url" : "https://youtube.com",
"description": "blablavlablablabla bla blablabla"
},
{
"name" : "Como fazer PIPOCA!",
"url" : "https://epic5.netlify.com",
"description": "blablavlablablabla bla blablabla"
},
{
"name": "Como fazer pipoca quente na manteiga!",
"url": "https://google.com",
"description": "pipoca r mt bom"
},
{
"name": "Como dançar beat it",
"url": "https://google.com",
"description": "pipoca r mt bom"
}
]
}
我的代码
let inputS = document.querySelector('.filterPosts');
let inputSearch = inputS.value.toUpperCase();
let pList = document.querySelector('.postsList');
let allLi = document.getElementsByTagName('li');
let requestURL = 'Posts.json';
let request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json'; request.send();
request.onload = function() {
let posts = request.response;
showPosts(posts);
search(posts);
}
function showPosts(jsonObj) {
let posts = jsonObj['posts'];
for (let i = 0; i < posts.length; i++) {
let listContent = document.createElement('a');
listContent.textContent = posts[i].name;
listContent.href = posts[i].url;
let liItem = document.createElement('li');
liItem.appendChild(listContent);
pList.appendChild(liItem);
}
}
function search(jsonObj) {
let t = jsonObj['posts'];
for (let i = 0; i < t.length; i++) {
txtValue = t[i].name;
if (txtValue.toUpperCase().indexOf(inputSearch) > -1) {
allLi[i].style.display = 'block';
} else {
allLi[i].style.display = 'none';
}
}
}
inputS.addEventListener('keyup',function(){
search();
});
在搜索功能中输入错误时,错误在于搜索功能内(让t = jsonObj ['posts'];),它返回未定义的
请帮助:(我正在尝试将json t [i] .name中的值与输入中输入的值进行比较,但我做不到
答案 0 :(得分:0)
我能够在您的代码中找到错误,我可以在here上正常工作,我拿出XMLHttpRequest
并将其放入变量中。问题是您在程序末尾调用search()
函数时没有任何参数。我也将比较行更改为
txtValue.toUpperCase().indexOf(inputSearch) == 0
因为我认为这样做更有意义,但是如果您希望将其搜索整个内容,也可以将其更改为> -1
。我希望这有帮助。我更改的另一件事是,我在search()
函数中添加了一行,检查了输入值并对其进行了更新,其代码为
let inputSearch = inputS.value.toUpperCase();
我希望这会有所帮助。