jQuery组合框自动完成(Autocomplete)是一种用户界面功能,当用户在输入框中键入时,会显示一个下拉列表,其中包含与用户输入匹配的建议选项。这种功能可以显著提升用户体验,特别是在处理大量可能选项时。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<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.js"></script>
</head>
<body>
<div class="ui-widget">
<label for="tags">选择项目: </label>
<input id="tags">
</div>
<script>
$( function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
} );
</script>
</body>
</html>
$( "#tags" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "search.php",
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 2,
select: function( event, ui ) {
console.log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
原因:
解决方案:
原因:
解决方案:
minLength
属性,减少过早触发搜索delay
选项延迟请求$( "#tags" ).autocomplete({
source: availableTags,
minLength: 3,
delay: 500
});
解决方案:
使用_renderItem
方法自定义显示
$( "#tags" ).autocomplete({
source: availableTags,
}).data("ui-autocomplete")._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label + "<br>" + item.desc + "</div>" )
.appendTo( ul );
};
$( "#tags" ).autocomplete({
source: availableTags,
select: function(event, ui) {
var terms = this.value.split(/,\s*/);
terms.pop(); // 移除当前输入的部分
terms.push(ui.item.value); // 添加选择的项
terms.push(""); // 添加空项
this.value = terms.join(", ");
return false;
},
focus: function() {
return false;
}
});
var data = [
{ label: "anders", category: "" },
{ label: "andreas", category: "" },
{ label: "antal", category: "" },
{ label: "annhhx10", category: "Products" },
{ label: "annk K12", category: "Products" },
{ label: "annttop C13", category: "Products" },
{ label: "anders andersson", category: "People" },
{ label: "andreas andersson", category: "People" },
{ label: "andreas johnson", category: "People" }
];
$( "#tags" ).autocomplete({
source: data,
minLength: 0
}).data("ui-autocomplete")._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label + "<span class='category'>" + item.category + "</span></div>" )
.appendTo( ul );
};
delay
选项减少频繁请求通过合理配置jQuery Autocomplete,可以显著提升表单的可用性和用户体验,同时减少用户输入错误。