javascript - 始终在 jQuery 自动完成中显示一个字符串,即使它与输入字符串不匹配
问题描述
我知道发布在以下位置的相同问题:始终在 jQuery Autocomplete 中显示特定选择,即使它与输入不匹配
问题是当使用上述问题中建议的 open 函数作为解决方案时,仅当自动完成列表中有匹配项时才会触发该事件。因此,当用户在搜索框中键入时,并不总是显示特定的选择。
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")
},
});
我想始终在最顶部显示“搜索为关键字”作为选项,无论用户在搜索框中输入时是否有匹配的字符串。目前,“搜索为关键字”仅在找到匹配字符串时显示在顶部。另外,是否有使“搜索为关键字”成为搜索表单中的可点击事件?请参阅 jsfiddle 以了解我所描述的内容。
解决方案
您可以将字符串的响应选项用于显示的标签数组:unshift
search 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">
推荐阅读
- mysql - 创建时间戳为同一天的新表
- android - Android Studio Gradle 问题 >> build.gradle': 1: unexpected token: <@line 1, column 1
- asp.net-core - 使用具有散列密码和盐的数据创建种子
- python - 如何处理意外按键
- python - 获取存储在 Python 中的二维列表中的特定字典值的数量
- saml - ITfoxtec SAML 2.0 会话超时
- angular - 如何在 Angular 2 中测试 ViewChildren 的变化
- laravel - 如何从数据库中为laravel中的不同页面动态元标记和元描述?
- node.js - Kafka-node 不断断开并重新连接“Kafka 生产者错误:NestedError refreshBrokenMetadata”
- django - 如何使用django在同一个浏览器中登录多个用户