我可以触发浏览器通过javascript显示自动填充建议吗?

Mik*_*ike 6 javascript html5

我正在使用html datalist为文本输入创建自动完成选项.我想知道是否可以在点击按钮时触发javascript中显示的建议,而不是双击输入.

<datalist id='gradeSuggestions'>
    <option value='A'>A</option>
    <option value='B'>B</option>
    <option value='C'>C</option>
</datalist>

<input name="grade[]" autocomplete="off" list='gradeSuggestions' type='text' />

<input type='button' id='showSuggestions' value='Show Suggestions' />

<script>
$('#showSuggestions').on('click', function(){
   // show the suggestions below the text input 
});
</script>
Run Code Online (Sandbox Code Playgroud)

这是一个jsFiddle

Tra*_*s J 2

jsFiddle Demo

如果您只想在第一次单击时显示自动完成功能,那么您可以进行一些焦点检测来触发它出现。当用户在输入上按下鼠标时,可以给予输入焦点。单击事件将冒泡,输入将认为输入被单击两次,从而导致显示自动完成。

$('#grade').mousedown(function(){
 if( document.activeElement == this )return;
 $(this).focus();
});
Run Code Online (Sandbox Code Playgroud)