2013-02-09 47 views

回答

2

這裏唯一的區別是,你需要確認並請撥打extractLast,就像您鏈接的演示所做的一樣。下面是完整的代碼應與多個值工作(特別注意的source選項):

$("#tags") 
    .on("keydown", function (event) { 
     if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) { 
      event.preventDefault(); 
     } 
    }) 
    .autocomplete({ 
     minLength: 0, 
     source: function (request, response) { 
      var term = $.ui.autocomplete.escapeRegex(extractLast(request.term)) 
       // Create two regular expressions, one to find suggestions starting with the user's input: 
       , startsWithMatcher = new RegExp("^" + term, "i") 
       , startsWith = $.grep(source, function(value) { 
        return startsWithMatcher.test(value.label || value.value || value); 
       }) 
       // ... And another to find suggestions that just contain the user's input: 
       , containsMatcher = new RegExp(term, "i") 
       , contains = $.grep(source, function (value) { 
        return $.inArray(value, startsWith) < 0 && 
         containsMatcher.test(value.label || value.value || value); 
       });    

      // Supply the widget with an array containing the suggestions that start with the user's input, 
      // followed by those that just contain the user's input. 
      response(startsWith.concat(contains)); 
     }, 
     focus: function() { 
      return false; 
     }, 
     select: function (event, ui) { 
      var terms = split(this.value); 
      terms.pop(); 
      terms.push(ui.item.value); 
      terms.push(""); 
      this.value = terms.join(", "); 
      return false; 
     } 
}); 

例子:http://jsfiddle.net/Aa5nK/1/

+0

謝謝!終於找到了我正在尋找的東西。整潔的解決方案 – iDev 2017-04-13 23:58:50

0

在響應中,你應該返回符合您在查詢想要什麼結果的列表:

例如

list_of_terms = {"term0","term1","term2",...}; 

$("#inputsearch").autocomplete({ 
    var term = request.term 
    var list = new Array(); 
    source: function(request, response) { 
     var cnt = 0; 
     $.each(list_of_terms, function(i) { 
      var rSearchTerm = new RegExp('^' + RegExp.quote(term),'i'); 
      if (list_of_terms[i].match(rSearchTerm)) {     
       list[cnt] = list_of_terms[i]; 
       cnt++; 
      } 
     }); 
    response(list); 
    } 
}); 



RegExp.quote = function(str) { 
    return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); 
}; 

提供我沒有錯過一個括號,這應該給你多個值在下拉列表中,如果輸入的一詞中的equals您list_of_terms陣列學期開始

+0

哪裏去這樣?看起來像這是代碼框 - RegExp.quote = function(str){return(str +'')。replace(/([。?* +^$ [] \(){} | - ])/ g, 「\ $ 1」); }; – 2013-02-09 14:04:54

+0

這是javascript。它進入JavaScript腳本標記。你將它鏈接到輸入框的輸入框ID – Tucker 2013-02-09 15:10:40

+0

此代碼在哪裏?'RegExp.quote = function(str){return(str +'')。replace(/([。?* +^$ [] \( ){} | - ])/ g,「\ $ 1」); };'去?因爲它在答案的灰色框外。 – 2013-02-09 15:55:37