我使用这段javascript代码来过滤搜索项,但我想过滤div元素,而不仅仅是纯文本。
var searchBox = document.querySelector("input");
var resultList = document.getElementById("resultList");
var resultsArray = [
"Walt Disney",
"Which color do you like?",
"Where are we?",
"Which wells are the best?",
"Who's on first?",
"Cowboys wear white",
"Wells are awesome!",
"Whoooppppeeeeee",
"Which Witch is Which",
"What's going on?",
"Well look at that!"
];
searchBox.addEventListener('keyup', function() {
var searchTerm = searchBox.value.toLowerCase();
// reset ul by removing all li items
while (resultList.hasChildNodes()) {
resultList.removeChild(resultList.lastChild);
}
// loop through array of sentences
for (var i = 0; i < resultsArray.length; i++) {
// if the array item starts with the search value AND the input box is not empty
if(resultsArray[i].toLowerCase().startsWith(searchTerm) && searchTerm != "") {
var li = document.createElement('li'); // create an li item
li.innerHTML = resultsArray[i]; // add the sentence to the new li item
resultList.append(li); // add new li item to resultList ul
}
}
// if resultList is empty after going through loop display 'no results found'
if (!resultList.hasChildNodes() && searchTerm != "") {
var li = document.createElement('li');
li.innerHTML = "no results found";
resultList.append(li);
}
});
我想将var resultsArray项更改为div类项,例如:“华特迪士尼”,改为
<div class="item"><a href="walt-disney.html"><img src="images/walt-disney.png" alt="walt disney" border="0" /></a>walt disney</div>
发布于 2018-07-07 07:09:25
将resultsArray
更改为对象数组,其中包含构造结果HTML所需的所有信息。
var resultsArray = [
{string: "Walt Disney", url: "walt-disney.html", img: "walt-disney.png", alt: "walt disney" },
{string: "Which color do you like?", url: "which-color.html", img: "which-color.png", alt: "which color" },
...
];
if (searchTerm != "") {
resultsArray.forEach(({string, url, img, alt} => {
// if the array item starts with the search value AND the input box is not empty
if(string.toLowerCase().startsWith(searchTerm)) {
var li = document.createElement('li'); // create an li item
li.innerHTML = `<div class="item"><a href="${url}"><img src="images/${img}" alt="${alt}" border="0" /></a>${string}</div>`
resultList.append(li); // add new li item to resultList ul
}
}
}
https://stackoverflow.com/questions/51218519
复制相似问题