Javascript 如何从数组项生成HTML?

Javascript 如何从数组项生成HTML?,javascript,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 t

我使用这个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 searchBox=document.querySelector(“输入”);
var resultList=document.getElementById(“resultList”);
var结果数组=[
“沃尔特·迪斯尼”,
“你喜欢什么颜色?”,
“我们在哪里?”,
“哪口井最好?”,
“谁先上场?”,
“牛仔穿白色”,
“水井太棒了!”,
“哇哦,
“哪个女巫是哪个”,
“发生了什么事?”,
“好吧,看看这个!”
];
searchBox.addEventListener('keyup',function(){
var searchTerm=searchBox.value.toLowerCase();
//通过移除所有li项目重置ul
while(resultList.hasChildNodes()){
resultList.removeChild(resultList.lastChild);
}
//循环排列句子
对于(var i=0;i
我想将var resultsArray项更改为div类项,例如:“Walt Disney”,更改为

沃尔特·迪斯尼
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
        }
    }
}
var resultsArray=[
{字符串:“沃尔特·迪斯尼”,url:“Walt Disney.html”,img:“Walt Disney.png”,alt:“沃尔特·迪斯尼”},
{string:“你喜欢哪种颜色?”,url:“Which color.html”,img:“Which color.png”,alt:“Which color”},
...
];
如果(searchTerm!=“”){
resultsArray.forEach(({string,url,img,alt}=>{
//如果数组项以搜索值开头,且输入框不为空
if(string.toLowerCase().startsWith(searchTerm)){
var li=document.createElement('li');//创建一个li项
li.innerHTML=`${string}`
resultList.append(li);//将新的li项添加到resultList ul
}
}
}

过滤文档元素数组的解决方案是查看它们的
innerHTML
属性,这是一个
字符串,我们可以使用它根据搜索词进行过滤

这里有一个可行的解决方案:

注意事项:

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'
  }
})
<input type='text' />
<ul id='resultList'>
</ul>
  • 为了简单起见,我在主体中创建了输入结果数组元素,然后使用
    queryselectoral()
    在脚本中抓取它们,然后使用
    Array.prototype.slice()
    将它们解析为
    数组
  • 在filter函数中,我查看这个输入元素列表数组的
    innerHTML
    属性以查找匹配项
var searchBox=document.querySelector(“输入”);
var resultList=document.getElementById(“resultList”);
//获取结果节点列表
var resultsNodeList=document.querySelectorAll(“#数组列表>div”);
//将节点列表解析为数组列表
var resultsArray=[].slice.call(resultsNodeList);
searchBox.addEventListener('keyup',function(){
var searchTerm=searchBox.value.toLowerCase();
//通过移除所有li项目重置ul
while(resultList.hasChildNodes()){
resultList.removeChild(resultList.lastChild);
}
//循环排列句子
对于(var i=0;i-1){
var li=document.createElement('li');//创建一个li项
li.appendChild(resultsArray[i]);//将句子添加到新的li项中
resultList.append(li);//将新的li项添加到resultList ul
}
}
//如果循环后resultList为空,则显示“未找到结果”
如果(!resultList.hasChildNodes()&&searchTerm!=“”){
var li=document.createElement('li');
li.innerHTML=“未找到任何结果”;
结果列表追加(li);
}
});
#数组列表{
显示:无;
}
#结果列表{
列表样式类型:无;
-webkit填充开始:20px;
}

沃尔特·迪斯尼
哪种颜色
我们在哪里
最佳油井


建议:
停止创建、追加和删除
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'
  }
})
<input type='text' />
<ul id='resultList'>
</ul>
const searchBox=document.querySelector(“输入”);
const resultList=document.getElementById(“resultList”);
常量结果数组=[
“沃尔特·迪斯尼”,
“你喜欢什么颜色?”,
“我们在哪里?”,
“哪口井最好?”,
“谁先上场?”,
“牛仔穿白色”,
“水井太棒了!”,
“哇哦,
“哪个女巫是哪个”,
“发生了什么事?”,
“好吧,看看这个!”
]
String.prototype.removeparchention=函数(){
返回此。替换(/['“`,!?:;。]/g')
}
String.prototype.toSnakeCase=函数(){
返回此.split('').join('-').removePerception().toLowerCase()
}
searchBox.addEventListener('keyup',function(){
const searchTerm=searchBox.value.toLowerCase().trim()
resultList.innerHTML=“”
如果(搜索术语){
const renderedHTML=resultsArray
.filter(result=>result.toLowerCase().indexOf(searchTerm)!=-1)
.map(结果=>`