首页 > 解决方案 > 如何将特定链接添加到搜索关键字

问题描述

这是我正在处理的搜索代码,但我想为数组“people”的成员提供特定链接,以便“rock”有自己的链接到另一个页面,“brock”,会有自己的链接等等开,搜索工作正常,但我希望结果链接到其他页面

在此处输入图像描述 在此处输入图像描述 这是代码(没有html)

    const people = [

      {name: 'david'},
      {name: 'patel'},
      {name: 'kevin'},
      {name: 'coco'},
      {name: 'brock'},
      {name: 'rock'}
  ];

      const list = document.getElementById('list');

      //function to set the list
      function setList(group){
          clearlist();
          for(const person of group)
              {
                  const item = document.createElement('a');
                  item.classList.add('list-group-item');
                  const text =document.createTextNode(person.name);
                  item.appendChild(text);
                  list.appendChild(item);
              }
          if(group.lenght==0){
              setnoresult();
          }
      }

      function clearlist(){
          while(list.firstChild)
              {
                  list.removeChild(list.firstChild);
              }
      }

      function setnoresult(){
          const item = document.createElement('li');
          item.classList.add('list-group-item');
          const text =document.createTextNode('no result found');
          item.appendChild(text);
          list.appendChild(item);
      }

      function getrelevancy(value, searchterm){
          if(value === searchterm)
              {
                  return 2;
              }
          else if(value.startsWith(searchterm))
          {
              return 1;
          }
          else if(value.includes(searchterm))
          {
              return 0;
          }
          else{
              return -1;
          }
      }

      const searchinput = document.getElementById('search');
      searchinput.addEventListener('input',(event) => {

          let value = event.target.value;
          if(value && value.trim().length >0)
              {
                  value = value.trim().toLowerCase();
                  setList(people.filter(person => {
                      return person.name.includes(value);
                  }).sort((personA, personB) =>{
                      return getrelevancy(personB.name, value- getrelevancy(personA.name ,value))
                  }));
              }
          else{
              clearlist();
          }
 //           console.log(event.target.value);
      })

标签: javascripthtml

解决方案


您可以像 alink: 'page.com到您的对象然后添加<a>链接item.href = people[index].link。很难解释,我举个例子:

const people = [ {name: "Jeff", link: "page.com/jeff"}, {name: "Jo", link: "page.com/Jo"} ];

然后setList像这样调用:

setList(people.filter(person => { return people.indexOf(person.name) }));

或类似的东西。然后通过以下方式设置href和名称:

const text = document.createTextNode(people[group].name);
item.href = people[group].link;

我真的希望你明白我刚才说的话。


推荐阅读