始终在 jQuery 自动完成中显示一个字符串,即使它与输入字符串不匹配

Always show a string in jQuery Autocomplete even if it doesn't match input string

我知道发布在以下位置的相同问题:Always show a specific choice in jQuery Autocomplete even if it doesn't match input

问题是当按照上述问题的建议使用打开函数作为解决方案时,只有当自动完成列表中有匹配项时才会触发事件。因此,当用户在搜索框中输入内容时,并不总是显示具体的选择。

https://jsfiddle.net/u1jwz6s4/

<html lang="en">
<head>
<meta charset="utf-8">
<title>autocomplete demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>

<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">

</body>
</html>

$( "#autocomplete" ).autocomplete({
source: [ "c++", "java", "php", "coldfusion", "javascript", "asp",    "ruby" ],
open: function(){
$('.ui-autocomplete').prepend("search by keyword")
},
});

我想始终将 "search as keyword" 作为选项显示在最顶部,无论用户在搜索框中键入时是否存在匹配的字符串。目前,"search as keyword" 只有在找到匹配的字符串时才会显示在顶部。另外,有没有办法让 "search as keyword" 成为搜索表单中的可点击事件?查看 jsfiddle 以了解我在描述什么。

您可以使用 response 选项来 unshiftsearch by keyword 字符串添加到显示标签的数组中:

const $input = $("#autocomplete");
$input.autocomplete({
  source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"],
  response: (event, ui) => {
    const label = 'search by keyword';
    ui.content.unshift({
      label,
      value: $input.val()
    });
  }
});
$(document).on('click', '.ui-autocomplete div:contains("search by keyword")', () => {
  console.log('searching for ' + $input.val());
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">