这是我正在使用的搜索代码,但我想给数组“ people”的成员提供特定的链接,以便“ rock”具有自己的链接到另一个页面“ brock”的链接。链接等,搜索工作正常,但我希望结果链接到其他页面
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);
})
答案 0 :(得分:0)
您可以在对象上添加link: '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;
我真的希望你能理解我刚才说的话。