【发布时间】:2019-08-24 23:37:52
【问题描述】:
这里是示例 App.js:
//filtering student list based on keyup search value
//array length is 0 if no match was found
search.addEventListener('keyup', (e) => {
// Check to see if search term is empty or not
if (e.target.value.length > 0) {
const noResults = document.querySelector(".no-results");
//how many student names matched the input
console.log(studentListItems[0].children[0].children[1].textContent);
const array = Array.from(studentListItems).filter(student => student.children[0].children[1].textContent.includes(e.target.value))
//No names filtered
//Every student item disappears, no-results li shows
if (array.length == 0) {
Array.from(studentListItems).forEach(student => {
student.style.display = "none";
});
noResults.style.display = "block";
replaceLinks(array)
//show ones that match, hide ones that don't
} else if (array.length > 0) {
displayPage(array,1)
replaceLinks(array)
Array.from(studentListItems).forEach(item => {
if (item.children[0].children[1].textContent.includes(e.target.value)) {
item.style.display = "block";
} else {
item.style.display = "none";
}
})
noResults.style.display = "none";
}
} else { // Display the initial state if search term is empty
displayPage(studentListItems, 1);
replaceLinks(studentListItems);
}
});
这是我的 JS fiddle 的链接:https://jsfiddle.net/6sa4702z/
当我在搜索输入中输入内容时,控制台会提示我“script.js:155 Uncaught TypeError: Cannot read property 'textContent' of undefined' for the filter function 将数组存储在名为 array
的 变量正如您所看到的,当您控制台记录 studentListItems 时,您会得到输出,所以我不明白为什么过滤器功能不起作用?
我也收到了一个表达式不可用的错误,我觉得这与此有关。这与变量范围有关吗?
【问题讨论】:
标签: javascript filter scope