【问题标题】:Twitter typeahead, Bloodhound filter startswithTwitter 提前输入,Bloodhound 过滤器以
【发布时间】:2014-11-17 13:58:32
【问题描述】:

我想使用“startswith”过滤器过滤结果。现在,下面的代码会抓取与结果中任何单独的单词匹配的所有内容。因此,当用户键入“ex”时,“example”和“one two example”都会被过滤掉。如何更改此行为,以便仅过滤掉“示例”?

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(''))
    }
});

【问题讨论】:

    标签: javascript twitter-bootstrap twitter typeahead bloodhound


    【解决方案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);
                    };
                };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      • 2010-11-30
      • 1970-01-01
      相关资源
      最近更新 更多