0

有没有办法让 jQuery Autosuggest 插件限制用户只能添加搜索结果中包含的选择项,但不能添加新的选择项?

我的意思是,如果我输入“joh”并且列表仅显示“John”,那么我应该无法将“Johnny”添加到所选项目。

编辑:我使用的是wuyuntao的版本。您应该改为查看hlsolutions 的

4

2 回答 2

0

事实证明,已经有这个功能的自动建议插件有一个更好的维护版本。看看这个:https ://github.com/hlsolutions/jquery-autosuggest

从旧的迁移到新的是无痛的。就像替换JS文件一样简单。

于 2013-08-05T14:28:58.140 回答
0

我想我设法做到了,但这基本上是在选择一个项目时恢复 Autosuggests 所做的一切。

将此添加到选项哈希中:

selectionAdded: function(elem) {
  var in_the_result_list = $.grep($('.as-results .as-list .as-result-item'), function(item) { return $(item).text() === elem.textNotChild() }).length;
  if (!in_the_result_list) {
    elem.remove();
    $('.as-input').html(elem.textNotChild());
    $('.as-values').val(function(i, current_value) {
      return current_value.replace(elem.textNotChild(), '');
    });
  }
}

也许有更好的方法来做到这一点?

PS:我正在使用自定义 jquery 方法来获取没有“x”的元素的文本,请随意以您想要的方式实现这一点。如果您需要,这是方法:

(function ($) {
  function elementText(el, separator) {
    var textContents = [];
    for(var chld = el.firstChild; chld; chld = chld.nextSibling) {
      if (chld.nodeType == 3) { 
        textContents.push(chld.nodeValue);
      }
    }
    return textContents.join(separator);
  }
  $.fn.textNotChild = function(elementSeparator, nodeSeparator) {
  if (arguments.length<2){nodeSeparator="";}
  if (arguments.length<1){elementSeparator="";}
    return $.map(this, function(el) {
      return elementText(el,nodeSeparator);
    }).join(elementSeparator);
  }
} (jQuery));
于 2013-08-05T09:02:59.930 回答