javascript - Twitter 提前输入,Bloodhound 过滤器开始

标签 javascript twitter-bootstrap twitter typeahead bloodhound

我想使用“startswith”过滤器来过滤结果。现在,下面的代码获取与结果中任何单独单词匹配的所有内容。因此,当用户输入“ex”时,“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(''))
    }
});

最佳答案

只需更改子字符串函数,如下所示:

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

关于javascript - Twitter 提前输入,Bloodhound 过滤器开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26974309/

相关文章:

javascript - 将 CSS 添加到 Javascript 小部件

html - 幽灵填充出现在 td 中,即使我删除了填充

Twitter-Bootstrap:导航栏中的登录表单

php - 需要在 php 中添加一个计数器以每 4 列分隔行

javascript - Jquery .each() - 返回值未定义

javascript - 使用 ng-repeat 时避免表中的列出现重复索引

php - 使用 PHP 和新的 Twitter API

javascript - 如何自定义默认 Twitter 小部件的 javascript 的默认 html 输出?

javascript - NodeJS - 从多级对象数组中提取数据

iphone - accountTypeWithAccountTypeIdentifier 未完成