Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在用户搜索内容时,如何使用JavaScript进行自动完成或建议?_Javascript_Autocomplete_Search Suggestion - Fatal编程技术网

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

在用户搜索内容时,如何使用JavaScript进行自动完成或建议?,javascript,autocomplete,search-suggestion,Javascript,Autocomplete,Search Suggestion,我是用HTML和Java脚本编写的,当用户写下他搜索的单词的第一个字母时,需要显示一个建议下拉菜单 我怎么做这个 <html> <body> <input type="text" id="myInput" autofocus="true"> <button id="btn" onclick="myfunction()">Search</button> <div id="outputArea" styl

我是用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>

搜寻
变量首字母缩写={
我的天啊,
lol:“大声说出来”,
lmao:“放过我的年龄”,
wtf:“此功能是什么”
};
var outputAreaRef=document.getElementById(“outputArea”);
函数myfunction(){
var word=document.getElementById(“myInput”).value.toLowerCase().trim();
如果(首字母缩略词[单词]!==未定义){word=首字母缩略词[单词];}
outputAreaRef.innerHTML=word;}

有一个HTML5元素可以让这变得非常简单。
数据列表
。您可以硬编码列表中的项目,也可以使用一些JS填充列表

您可以在数据列表上看到此答案的其他选项。

如果使用JS进行填充,则标记的最终外观如下:

(功能(浏览器){
函数附加项(列表、容器){
列表.forEach(功能(项){
const option=document.createElement('option');
option.setAttribute('值',项);
container.appendChild(可选);
});
}
const browserList=['internetexplorer','Firefox','Chrome','Opera','Safari','Brave'];
附加项(浏览器列表、浏览器);
}(document.getElementById(“浏览器”)
搜索浏览器