2

我需要添加一些功能到jQuery UI自動搜索功能。我想要解決的問題是允許用戶按任何順序輸入文本,以搜索術語列表並顯示建議。例如,假設我有以下方面:jQuery UI自動搜索搜索多個字符串

the brown cow jumped over the moon 
the blue cow watched in horror 
the red cow simply laughed 
the green cow got sick at such a sight 
the yellow cow lost 5 bucks to the black cow 
the black cow smiled at his fortune 

If the user types in "the cow", I would expect the autocomplete feature to list all the results. 
If I type in "brown moon", I would expect the first result to appear. 
If I type in "fortune smiled", the last result would appear. 

基本上這種行爲允許用戶鍵入任何順序任何字符串並獲得搜索結果。

這是我在想什麼。我需要在「打開」或「搜索」事件中添加回調函數,並在那裏處理結果。這是我的代碼到目前爲止:

$(function() 
{ 
    var data = 
    [ 
     "the brown cow jumped over the moon", 
     "the blue cow watched in horror", 
     "the red cow simply laughed ", 
     "the green cow got sick at such a sight", 
     "the yellow cow lost 5 bucks to the black cow", 
     "the black cow smiled at his fortune" 
    ]; 

    $(".text-search").autocomplete(
    { 
     autoFocus: true, 
     source: data, 
     delay: 0, 
     minLength: 2, 
     open: function (e, ui) 
     { 
      debugger; 
      // what should i do here? 
     }, 
     search: function (e, ui) 
     { 
      debugger; 
      // what should i do here? 
     } 
    }); 
}); 

<div class="ui-widget"> 
    <label for="autocomplete">Autocomplete: </label> 
    <input class="text-search"> 
</div> 
+0

你要求的方式根據搜索條件或如何使用自動完成調用服務器URL得到的結果和渲染的結果,語義搜索? –

回答

1

我會根據用戶輸入的文本創建自己的正則表達式。然後,您可以使用此正則表達式候選名單,以測試每個項目:

$(".text-search").autocomplete({ 
    autoFocus: true, 
    source: function(request, response) { 
     var regexStr = "\\b(" + $.map($.trim(request.term).split(" "), function(term) { 
      return $.ui.autocomplete.escapeRegex($.trim(term)) 
     }).join("|") + ")\\b", 
     matcher = new RegExp(regexStr); 

     response($.grep(data, function(value) { 
      return matcher.test(value.label || value.value || value); 
     })); 
    }, 
    delay: 0, 
    minLength: 2 
}); 

正則表達式一塊看上去很神祕,但它只是產生交替使用(|)的表達式。例如,如果輸入,則會生成\b(brown|cow)\b,它將匹配任何帶有「brown」或「cow」的字符串。

例子:http://jsfiddle.net/hTfj9/