首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从数组项生成HTML?

如何从数组项生成HTML?
EN

Stack Overflow用户
提问于 2018-07-07 06:53:08
回答 1查看 350关注 0票数 1

我使用这段javascript代码来过滤搜索项,但我想过滤div元素,而不仅仅是纯文本。

代码语言:javascript
复制
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类项,例如:“华特迪士尼”,改为

代码语言:javascript
复制
 <div class="item"><a href="walt-disney.html"><img src="images/walt-disney.png" alt="walt disney" border="0" /></a>walt disney</div> 
EN

回答 1

Stack Overflow用户

发布于 2018-07-07 07:09:25

resultsArray更改为对象数组,其中包含构造结果HTML所需的所有信息。

代码语言:javascript
复制
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
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51218519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档