jQuery UI Autocomplete(自动完成)实例
Autocomplete是 jQuery UI 中非常实用的组件,用于输入框提供智能建议列表,支持本地数据、远程 AJAX 数据、分类显示、自定义渲染等。常用于搜索框、标签输入、地址补全等场景。
官方演示地址:https://jqueryui.com/autocomplete/
下面提供几个渐进实例,从基础到高级,代码使用最新 CDN,可直接复制到 HTML 文件测试。
1.基础本地数据自动完成
使用数组作为数据源。
<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>jQuery UI Autocomplete 基础示例</title><linkrel="stylesheet"href="//code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css"><scriptsrc="//code.jquery.com/jquery-3.6.0.min.js"></script><scriptsrc="//code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script></head><body><label>编程语言:</label><inputid="autocomplete"><script>$(function(){varlanguages=["JavaScript","Java","Python","C++","C#","PHP","Ruby","Go","Swift","Kotlin"];$("#autocomplete").autocomplete({source:languages,minLength:2// 输入至少2个字符才触发建议});});</script></body></html>2.带标签的对象数据 + 分类显示
使用对象数组,支持label(显示)和value(选中后填充值),并实现分类。
<script>vardata=[{label:"JavaScript",category:"前端"},{label:"HTML",category:"前端"},{label:"CSS",category:"前端"},{label:"Java",category:"后端"},{label:"Python",category:"后端"},{label:"Node.js",category:"后端"}];$("#autocomplete").autocomplete({source:data,minLength:1,// 自定义分类菜单_renderMenu:function(ul,items){varthat=this;varcurrentCategory="";$.each(items,function(index,item){if(item.category!=currentCategory){ul.append("<li class='ui-autocomplete-category'>"+item.category+"</li>");currentCategory=item.category;}that._renderItemData(ul,item);});}});</script><style>.ui-autocomplete-category{font-weight:bold;background:#eee;padding:5px;}</style>3.自定义渲染(带图标或图片)
使用_renderItem自定义下拉项显示。
<script>$("#autocomplete").autocomplete({source:[{label:"Apple",icon:"https://via.placeholder.com/30?text=A"},{label:"Banana",icon:"https://via.placeholder.com/30?text=B"},{label:"Orange",icon:"https://via.placeholder.com/30?text=O"}]}).data("ui-autocomplete")._renderItem=function(ul,item){return$("<li>").append("<div><img src='"+item.icon+"' style='width:30px;vertical-align:middle;margin-right:10px;'>"+item.label+"</div>").appendTo(ul);};</script>4.远程数据源(AJAX)
从服务器动态获取数据(模拟可用数据)。
<script>$("#autocomplete").autocomplete({source:function(request,response){$.ajax({url:"https://api.example.com/search",// 替换为你的APIdata:{term:request.term},success:function(data){response($.map(data,function(item){return{label:item.name,value:item.id};}));}});},minLength:2,delay:300// 延迟请求,防频繁输入});</script>5.事件监听(select、change)
<script>$("#autocomplete").autocomplete({// ...select:function(event,ui){console.log("选中: "+ui.item.label+" (值: "+ui.item.value+")");},change:function(event,ui){if(!ui.item)console.log("未从列表中选择");}});</script>小技巧:
minLength: 0可实现点击输入框即显示全部建议。- 支持多选(Multiple values):查看官方 “Multiple, remote” 示例。
- 移动端友好,默认支持触摸。
如果你需要多选标签输入、结合 AJAX 从数据库搜索的完整后端示例,或带加载动画的版本,请告诉我更多需求!