如何有选择地禁用jQuery UI自动完成下拉列表项列表项

时间:2016-09-11 01:29:48

标签: jquery jquery-ui drop-down-menu jquery-ui-autocomplete jquery-widgets

默认情况下,下拉列表classesul.ui-autocomplete li.ui-menu-item。我想让不可选择的li无法选择更好的用户体验。即如果我在搜索栏中输入关键词“coat”,它会显示Mens Suggestions,然后是Jacket,然后是Women Suggestions,然后是Sweater。当我使用箭头键选择它们时,它会跳过建议部分。我尝试了.attr('disabled', ture);, .prop('disabled', true);user-select: none;没有一个正在运作。它只是将disabled="disabled"添加到li,它仍然可以选择。在jQuery UI中是否有一个禁用的属性我可以将它附加到li来完成此操作吗?

<ul class="ui-autocomplete">
 <li class="unselectable" >Mens Suggestions</li>
 <li>Jacket</li>
 <li class="unselectable" >Women Suggestions</li>
 <li>Sweater</li> 
</ul>

1 个答案:

答案 0 :(得分:1)

简短的回答是将课程设置为ui-autocomplete-category,如https://jqueryui.com/autocomplete/#categories

中的示例所示

工作示例:https://jsfiddle.net/Twisty/183he51q/

<强> HTML

<label for="search">Search: </label>
<input id="search">

<强> CSS

.ui-autocomplete-category {
  font-weight: bold;
  padding: .2em .4em;
  margin: .8em 0 .2em;
  line-height: 1.5;
}

<强>的jQuery

$(function() {
  $.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("<li class='ui-autocomplete-category'>" + item.category + "</li>");
          currentCategory = item.category;
        }
        li = that._renderItemData(ul, item);
        if (item.category) {
          li.attr("aria-label", item.category + " : " + item.label);
        }
      });
    }
  });
  var data = [{
    label: "Jacket",
    category: "Mens Suggestions"
  }, {
    label: "Sweater",
    category: "Mens Suggestions"
  }, {
    label: "Jacket",
    category: "Women Suggestions"
  }, {
    label: "Sweater",
    category: "Women Suggestions"
  }];

  $("#search").catcomplete({
    delay: 0,
    source: data
  });
});