jquery自动
jQuery自动完成功能实现
jQuery可以通过插件或原生方法实现自动完成功能,以下是几种常见方式:
使用jQuery UI Autocomplete
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<input id="tags">
<script>
$( function() {
var availableTags = ["选项1", "选项2", "选项3"];
$("#tags").autocomplete({
source: availableTags
});
} );
</script>
使用jQuery Ajax实现远程数据源
$("#search").autocomplete({
source: function(request, response) {
$.ajax({
url: "/api/search",
dataType: "json",
data: { term: request.term },
success: function(data) {
response(data);
}
});
},
minLength: 2
});
自定义自动完成功能
对于不需要插件的简单实现:
$("#input-field").on("input", function() {
var inputVal = $(this).val();
if(inputVal.length > 0) {
$.get("/suggestions", {q: inputVal}, function(data) {
$("#suggestions-container").html(
data.map(item => `<div class="suggestion">${item}</div>`).join("")
);
});
}
});
自动完成最佳实践
-
设置延迟触发(防抖处理)
var timer; $("#search").keyup(function() { clearTimeout(timer); timer = setTimeout(function() { // 执行搜索逻辑 }, 300); }); -
高亮匹配文本
.ui-autocomplete .ui-state-active { background: #F0F0F0; border-color: #CCC; } -
移动端适配需增加触摸事件支持

$(".suggestion-item").on("touchstart click", function() { $("#input-field").val($(this).text()); });
以上方法可根据项目需求选择使用,jQuery UI版本提供了最完整的解决方案,而自定义实现则更灵活轻量。






