2014-11-17 65 views
0

我想用'startswith'過濾器過濾結果。現在,下面的代碼抓住了匹配結果中任何單獨單詞的所有內容。所以當用戶輸入「ex」時,「example」和「two two example」都被過濾掉。我如何改變這種行爲,所以只有「example」被過濾掉了?Twitter typeahead,Bloodhound過濾器開始

var repos; 

repos = new Bloodhound({ 
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), 
queryTokenizer: Bloodhound.tokenizers.whitespace, 
limit: 10, 
    prefetch: { 
     name: 'terms', 
     url: 'search.php', 
    } 
}); 

repos.initialize(); 

$('input.typeahead').typeahead(null, { 
    name: 'repos', 
    source: repos.ttAdapter(), 
    templates: { 
     empty: '<div class="empty-message">No matches.</div>', 
     suggestion: Handlebars.compile([ 
      '<div class="term-box" id="{{id}}">', 
      '<p class="term">{{termname}}</p>', 
      '</div>' 
     ].join('')) 
    } 
}); 

回答

1

只需更改子功能是這樣的:

var substringMatcher = function (strs) { 
       return function findMatches(q, cb) { // an array that will be populated with substring matches 
        var matches = []; 

        // regex used to determine if a string contains the substring `q` 
        //var substrRegex = new RegExp(q, 'i'); 

        // we use starts with instead of substring 
        var substrRegex = new RegExp('^' + q, 'i'); 


        // iterate through the pool of strings and for any string that 
        // contains the substring `q`, add it to the `matches` array 
        $.each(strs, function (i, str) { 
         if (substrRegex.test(str)) { 
          matches.push(str); 
         } 
        }); 

        cb(matches); 
       }; 
      }; 
相關問題