如何在用户搜索某些内容时使用 JavaScript 进行自动完成或建议?



>我用HTML和Java脚本做了这个,并且当用户写下他搜索的单词的第一个字母时,需要提出建议

下拉菜单我该怎么做?

<html>
<body>
<input type="text" id="myInput" autofocus="true">
<button id="btn" onclick="myfunction()">Search</button>
<div id="outputArea" style="font-size: 30px"></div>
<script>
var acronyms = {
omg: "Oh My God",
lol: "Lough Out Loud",
lmao: "Lough My Age Off",
wtf: "What This Function"
};
var outputAreaRef = document.getElementById("outputArea");
function myfunction(){
var word = document.getElementById("myInput").value.toLowerCase().trim();
if (acronyms[word] !== undefined) {word = acronyms[word];}
outputAreaRef.innerHTML = word;}
</script>
</body>
</html>

有一个HTML5元素使这变得非常容易。datalist标记。您可以对列表中的项进行硬编码,也可以使用一些 JS 来填充列表。

对于数据列表中的其他选项,您可以看到此答案。 来自 javascript 中数组的 HTML 数据列表值

如果使用 JS 进行填充,则标记最终如下所示:<datalist id="browsers"> <option value="Internet Explorer"> <option value="Firefox"> <!-- more items here --> </datalist>

(function(browsers) {
function addItems (list, container) {
list.forEach(function(item){
const option = document.createElement('option');
option.setAttribute('value', item);
container.appendChild(option);
});
}
const browserList = ['Internet Explorer','Firefox','Chrome','Opera','Safari','Brave'];
addItems(browserList, browsers);
}(document.getElementById('browsers')));
<label for="autocomplete">Search for Browsers</label>
<input id="autocomplete" list="browsers">
<datalist id="browsers"></datalist>

最新更新