5

我正在使用 jqueryui 自动完成小部件来自动完成“国家”字段,但我遇到了一个问题。假设用户输入“in”,我希望 jqueryui 列出以“in”开头的“india”、“indonesia”等国家,但它也列出了名称中有“in”的国家(如:argentina) . 我该如何解决这个问题?

jQuery(".autocomplete").autocomplete({
    source: CountrySuggestions, //CountrySuggestions is an array in javascript containing the list of countries
    minLength: 2
});

阿克谢

4

1 回答 1

3

不幸的是,似乎 jQueryUI 自动完成功能不允许在数组源上执行此操作。但是,您可以挂钩插件的_initSource函数以在搜索中强制使用“开头”正则表达式标记 ( ^ ),如下所示。

我认为这可能被忽略了,因为它的大部分使用被认为是在远程检索中。无论哪种方式,都不是一个很好的解决方案,但由于正则表达式剥离功能,这是唯一想到的解决方案。

$.ui.autocomplete.prototype._initSource = function() {
  var array,
    url;
  if ( $.isArray(this.options.source) ) {
    array = this.options.source;
    this.source = function( request, response ) {
      // escape regex characters
      var matcher = new RegExp( "^"+$.ui.autocomplete.escapeRegex(request.term), "i" );
      response( $.grep( array, function(value) {
        return matcher.test( value.label || value.value || value );
      }) );
    };
  } else if ( typeof this.options.source === "string" ) {
    url = this.options.source;
    this.source = function( request, response ) {
      $.getJSON( url, request, response );
    };
  } else {
    this.source = this.options.source;
  }
};

$("#countries").autocomplete({
  source: ["India","Indonesia","Argentina"],
  minLength: 2
});
于 2010-04-30T17:53:36.900 回答