我有兴趣实现此处找到的解决方案(jQuery UI 自动完成文本框中的多个值),但使用外部 JSON 文件而不是硬编码数据集。有人可以帮忙吗?
要使用外部 JSON 文件在文本框中实现具有多个值的 jQuery UI 自动完成,您可以按照以下步骤操作:
加载JSON文件:使用jQuery的
getJSON
方法获取外部JSON数据。
初始化自动完成: 将数据绑定到自动完成小部件。
这是一个例子:
<input id="tags" type="text" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
$(document).ready(function() {
// Load the JSON file
$.getJSON('path/to/your/file.json', function(data) {
// Autocomplete with multiple values
$("#tags").autocomplete({
source: function(request, response) {
// Split the input by commas and get the last term for suggestions
var term = request.term.split(/,\s*/).pop();
// Filter the data for matching terms
response($.ui.autocomplete.filter(data, term));
},
focus: function() {
// Prevent value insertion on focus
return false;
},
select: function(event, ui) {
var terms = this.value.split(/,\s*/);
// Remove the current input
terms.pop();
// Add the selected item
terms.push(ui.item.value);
// Add a placeholder for the next term
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
});
</script>
file.json
):["Apple", "Banana", "Orange", "Pineapple", "Strawberry"]
此设置将从外部 JSON 文件中提取建议,并允许文本框中存在多个值,以逗号分隔。