javascript - 如何将特定链接添加到搜索关键字
问题描述
这是我正在处理的搜索代码,但我想为数组“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);
})
解决方案
您可以像 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;
我真的希望你明白我刚才说的话。
推荐阅读
- python - 如何将一列与另一列连接起来 - 熊猫
- jupyter-notebook - 如何使 Jupyter SQL 突出显示的单元格可执行?
- typescript - TypeScript:传递对象的方法作为参数调用
- python - 使用matplotlib进行条件着色?
- string - Lua - 如何使用中间带有变量 %d 的字符串创建 if 条件?
- sql - 尝试使用 rowid 作为外键时,sqlite 中的外键不匹配错误
- arrays - 仅用 Julia 中另一个数组的值替换数组中的零
- haskell - 非法镜头 Haskell
- python - django.core.exceptions.FieldError:为客户指定的未知字段(标题)
- swift - zsh:找不到命令:pod。Xcode