如何修改jQuery Autocomplete代码实现属性分行显示
问题
我在开发ASP.NET Web API时,用jQuery Ajax调用接口给Autocomplete组件返回数据,现在下拉选项是把Id、Name、Designation用连字符拼成一行显示:
Id - Name - Designation
想要改成每行单独显示一个属性,格式如下:
Id : 121 Name : michel nicol Designation : It Manager
解决方法
按以下几点修改代码即可实现需求:
1. 修改下拉项的标签内容
在$.map生成下拉项时,把原来的连字符-替换成HTML换行标签<br>,让每个属性单独占一行:
label: "File No : " + item.EmployeeID + "<br>Name : " + item.EmployeeName + "<br>Designation : " + item.Designation
2. 开启Autocomplete的HTML解析支持
在Autocomplete的配置里加上html: true,这样组件才会识别并渲染label里的HTML标签:
html: true
3. 清理重复的jQuery UI脚本
当前页面重复引入了多个版本的jQuery UI,会导致冲突,只保留一个最新的版本即可,比如保留1.12.0版本的引用:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" /> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
4. 可选:优化下拉项样式
如果觉得行间距太挤,可以加一段CSS调整行高和内边距:
.ui-autocomplete .ui-menu-item div { line-height: 1.5; padding: 6px 12px; }
修改后的完整代码
JavaScript代码
$("#txtDirectManagerId").autocomplete({ source: function (request, response) { var searchTextDirectManager = $("#txtDirectManagerId").val(); console.log("search text" + searchTextDirectManager) $.ajax({ url: '@Url.Action("GetAllEmployeeBasedSearchTextDirectManager", "Resignation")', data: { searchTextDirectManager: searchTextDirectManager }, method: "GET", dataType: "json", success: function (data) { response($.map(data, function (item) { return { label: "File No : " + item.EmployeeID + "<br>Name : " + item.EmployeeName + "<br>Designation : " + item.Designation, value: item.EmployeeID, employeeName: item.EmployeeName }; })) } }); }, position: { my: "right top", at: "right bottom" }, appendTo: '#searchContainerDirector', select: function (event, ui) { $("#DirectManagerName").val(ui.item.employeeName); }, minLength: 4, html: true // 开启HTML解析,让换行标签生效 });
内容的提问来源于stack exchange,提问作者ahmed abdelaziz
相关产品推荐
相关产品推荐

