如何从数组项生成HTML?

时间:2018-07-06 22:53:08

标签: javascript

我正在使用此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> 

3 个答案:

答案 0 :(得分:1)

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
        }
    }
}

答案 1 :(得分:1)

停止创建,附加和删除HTMLElement,这很麻烦

为避免大量for循环并使用document.createElement.appendChild.removeChild。我建议使用.innerHTML。除此之外,无需将resultArray中的项目列表重写为一个对象,只需修改字符串以匹配每个属性的要求,就像这样:

JavaScript代码:

const searchBox = document.querySelector("input");
const resultList = document.getElementById("resultList");
const 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!"
]

String.prototype.removePunctuation = function() {
  return this.replace(/['"`,!?:;.]/g, '')
}

String.prototype.toSnakeCase = function() {
  return this.split(' ').join('-').removePunctuation().toLowerCase()
}

searchBox.addEventListener('keyup', function() {
  const searchTerm = searchBox.value.toLowerCase().trim()
  resultList.innerHTML = ''

  if (searchTerm) {
    const renderedHTML = resultsArray
      .filter(result => result.toLowerCase().indexOf(searchTerm) !== -1)
      .map(result => `
        <div class='item'>
          <a href='${result.toSnakeCase()}.html'>
            <img src='images/${result.toSnakeCase()}.png' alt='${result.removePunctuation()}' border='0'/>
          </a>
        </div>
      `)

    resultList.innerHTML = renderedHTML.length > 0 ? renderedHTML.join('') : 'No results found'
  }
})

HTML代码:

<input type='text' />
<ul id='resultList'>
</ul>

以下是我对您的代码所做的更改:

  • 使用<ul>删除.innerHTML = ''中的所有元素
  • .trim() 空格,然后搜索。
  • 使用 resultsArray 遍历.filter
    • 这使我们能够确定在将所有内容保持在数组中的同时是否应显示项目。
  • 然后,我们可以使用 .map 生成HTML。
    • 那是如何工作的?我们正在使用模板字符串将值插入要插入.innerHTML
    • 的字符串中

您还将注意到我已经创建了String.prototype.removePunctuationString.prototype.toSnakeCase。我认为,尽管我并不总是建议修改String.prototype,但它的确使该代码更具可读性。将其转换为常规函数并不难。

认为它行不通吗? Test out a working version here on JSFiddle

仅供参考,在您的问题中,您需要一个div,其中a包含一个img。唯一显示的文本是alt='...'属性,因此,如果要显示resultsArray的文本,则应仅使用字符串插值:${result}

答案 2 :(得分:0)

过滤文档元素数组的解决方案是查看它们的innerHTML属性,这是一个string,我们可以根据搜索词对其进行过滤。

这是一个可行的解决方案:

注释:

  • 为简单起见,我在主体中创建了input resultArray元素,然后使用querySelectorAll()将其捕获到脚本中,然后使用Array将其解析为Array.prototype.slice()。 / li>
  • 在过滤器功能中,我正在查看此输入元素列表数组的innerHTML属性以找到匹配项。

var searchBox = document.querySelector("input");
var resultList = document.getElementById("resultList");
// Get the results nodes list
var resultsNodeList = document.querySelectorAll('#array-list>div');
// Parse the node list into an array list
var resultsArray = [].slice.call(resultsNodeList);


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(searchTerm != "" && resultsArray[i].innerHTML.toLowerCase().indexOf(searchTerm) > -1) {
      var li = document.createElement('li'); // create an li item
      li.appendChild(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);
  }
});
#array-list{
 display: none; 
}
#resultList{
  list-style-type: none;
  -webkit-padding-start: 20px;
}
<div id="array-list">
  <div class="item"><a href="walt-disney.html"><img src="images/walt-disney.png" alt="walt disney" border="0" /></a>walt disney</div>
  <div class="item"><a href="which-color.html"><img src="images/color.png" alt="which color" border="0" /></a>which color</div>
  <div class="item"><a href="where.html"><img src="images/where.png" alt="where are we" border="0" /></a>where are we</div>
  <div class="item"><a href="best-wells.html"><img src="images/best-wells.png" alt="best wells" border="0" /></a>best wells</div>
</div>

<input type="text" placeholder="Type something to search">
<br><br>
<span>Suggestions:</span>
<ul id="resultList">

</ul>