gpt4 book ai didi

javascript - 如何添加特定链接以搜索关键字

转载 作者:行者123 更新时间:2023-11-28 02:20:25 25 4
gpt4 key购买 nike

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

enter image description here enter image description here这是代码(没有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);
})

最佳答案

你可以像 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;

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

关于javascript - 如何添加特定链接以搜索关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57983655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com