如何在AutoComplete中找出所选元素的类别?

我需要对AutoComplete结果进行分组,我发现了以下解决方案 。 如何确定所选建议的类别?

例如,假设有城市和国家类别,用户选择其中一个城市。 我怎么知道所选项目是城市的一部分而不是国家类别(当表格提交时)? 我也不希望用户可以看到类别名称。

到目前为止我发现了什么

$.widget( "custom.catcomplete", $.ui.autocomplete, { _renderMenu: function( ul, items ) { var self = this, currentCategory = ""; $.each( items, function( index, item ) { if ( item.category != currentCategory ) { ul.append( "
  • " + item.category + "
  • " ); currentCategory = item.category; } self._renderItem( ul, item ); }); } });

    我的代码

     $(function() { $("#box1").autocomplete({ source: function(e, r) { var t, s = "http://localhost:8080/MyProject/autoComplete/box1"; $.ajax({ url: s, dataType: "json", data: { q: e.term }, success: function(e) { r(e) } }) }, select: function(event, ui) { if (ui.item) { alert("box one is seleted"); } }, }), $("#box2").autocomplete({ source: function(e, r) { $.ajax({ url: "http://localhost:8080/MyProject/autoComplete/box2", dataType: "json", data: { q: e.term }, success: function(e) { r(e) } }) }, select: function(event, ui) { if (ui.item) { alert("box two is selected"); } }, }) 

    更新

    我也找到了这个代码,但无法弄清楚这个类别。

    您需要在source获得的response包含该类别。 建议的项目可以具有valuelabel更多的属性。 在您的示例中,他们使用类别。 如果您提供的数据格式正确,那么它只是您可以使用select事件上的简单ui.item.category访问的项目的property

    像这样:

     $.widget("custom.catcomplete", $.ui.autocomplete, { _create: function() { this._super(); this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)"); }, _renderMenu: function(ul, items) { var that = this, currentCategory = ""; $.each(items, function(index, item) { var li; if (item.category != currentCategory) { ul.append("
  • " + item.category + "
  • "); currentCategory = item.category; } li = that._renderItemData(ul, item); if (item.category) { li.attr("aria-label", item.category + " : " + item.label); } }); } }); $("#search").catcomplete({//make sure you call your custom autocomplete delay: 0, source: function(request, callback) { callback(data); //here you must make sure the response you're getting has category. }, select: function(e, ui) { // if the cateogry is in your response, on select, your item will have a category property. alert('Item category: ' + ui.item.category) } }); // Modify your response so you have something similar to this. var data = [{ 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" }];
     .ui-autocomplete-category { font-weight: bold; padding: .2em .4em; margin: .8em 0 .2em; line-height: 1.5; }