gpt4 book ai didi

javascript - 如何使用输入进行自动完成搜索?

转载 作者:行者123 更新时间:2023-12-03 01:30:08 25 4
gpt4 key购买 nike

我需要 jquery 或 javascript 来自动完成下拉列表,其中包含我的搜索输入结果。我需要结果作为链接“”,以便我可以在新选项卡中打开它或通过单击直接打开它。这是我的代码:

<input type="text" id="searchinput" class="search-input" placeholder="Search here.." />

<ul id="main-menu">
<li class="has-sub"><a href="javascript:;"><span class="title">Menu Header1</span></a>
<ul>
<li><a href="example.com"><span class="childtitle">brand one</span></a></li>
<li><a href="example.com"><span class="childtitle">brand two</span></a></li>
</ul>
</li>

<li class="has-sub"><a href="javascript:;"><span class="title">Menu Header2</span></a>
<ul>
<li><a href="example.com"><span class="childtitle">Car BMW</span></a></li>
<li><a href="example.com"><span class="childtitle">Car Toyota</span></a></li>
<li><a href="example.com"><span class="childtitle">Car Opel</span></a></li>
<li><a href="example.com"><span class="childtitle">Car Kia</span></a></li>
</ul>
</li>
</ul>

最佳答案

纯 JavaScript 中的可能解决方案。

  • 创建标签数组,您将与输入匹配
  • 为输入字段设置input事件监听器
  • 在每个 input 事件上,清除列表元素的内容并基于某些匹配函数动态创建新元素,添加每个匹配字符串的链接

// array of values to match against
const tags = ['bmw', 'toyota', 'opel', 'kia'];

// fetch input and list elements
const input = document.querySelector('input');
const list = document.querySelector('ul');

// simple match function, performs substing matching
const getMatch = (toMatch, tags) =>
tags.filter((tag) => tag.includes(toMatch.toLowerCase()));

input.addEventListener('input', (event) => {
// clear contents of list
list.innerHTML = '';

// start matching only when input field is non-empty
if (input.value !== '') {
// call matching function and create a link for each
// item returned by it
getMatch(input.value, tags).forEach((match) => {
const item = document.createElement('li');
list.append(item);

const link = document.createElement('a');
item.append(link);

// add href attribute and text dynamically
link.setAttribute('href', `www.example.com/${match}`);
link.textContent = match;
});
}
});
Search: <input type="text">
<ul></ul>

关于javascript - 如何使用输入进行自动完成搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51342104/

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