代码之家  ›  专栏  ›  技术社区  ›  rebelliard

在多个字段中进行Twitter Bootstrap的类型广告搜索

  •  4
  • rebelliard  · 技术社区  · 11 年前

    默认情况下 typeahead plugin 使用单个数据源来获取结果。我想让它在多个字段中搜索,所以如果说,我有:

    var items = [
        {'title': 'Acceptable', 'description': 'Good, but not great'}
    ]
    

    它将在 title description 字段,最好是通过AJAX。

    这个插件可以做到这一点吗?

    2 回复  |  直到 11 年前
        1
  •  2
  •   pickypg    11 年前

    Typeahead不支持在没有两个调整的情况下使用JSON对象。Github中很少有拉取请求,我已经 submitted one myself ,但目前,您必须手动覆盖 select render 。此外,您还必须覆盖 highlighter , matcher , sorter updater ,但这些可以通过传递到typeahead中的选项来完成。

    var typeahead = control.typeahead({ /* ... */ }).data('typeahead');
    
    // manually override select and render
    //  (change attr('data-value' ...) to data('value' ...))
    //  otherwise both functions are exact copies
    typeahead.select = function() {
        var val = this.$menu.find('.active').data('value')
        this.$element.val(this.updater(val)).change()
        return this.hide()
    };
    typeahead.render = function(items) {
        var that = this
    
        items = $(items).map(function (i, item) {
            i = $(that.options.item).data('value', item)
            i.find('a').html(that.highlighter(item))
            return i[0]
        });
    
        items.first().addClass('active')
        this.$menu.html(items)
        return this
    };
    

    如果你需要其他方面的帮助,请告诉我,但要点是:

    control.typehead({
        matcher: function (item) {
            var lcQuery = this.query.toLowerCase();
            return ~item.title.toLowerCase().indexOf(lcQuery)
                || ~item.description.toLowerCase().indexOf(lcQuery);
        }
    };
    

    我还有一个 JFiddle example 与我提出的拉取请求有关,但在2.3.1中,甚至3.x中都不存在排序功能,而拉取请求未被接受,因此您必须重写 分拣机 以有效地重复我所做的一切 匹配器 以上(排序时同时检查两者)。

    至于AJAX调用,您可以覆盖 source 方法,以获取AJAX功能。通过不返回 来源 调用时,它假设第二个参数, process, 将被调用并得到结果。

    control.typehead({
        minLength: 3,
        source: function(query, process) {
            $.ajax({
                url: url + encodeURIComponent(query),
                type: 'GET',
                success: process,
                error: function() { /* ... */ }
            });
        }
    });
    
        2
  •  0
  •   Myk Klemme    9 年前

    Typeahead在v10.3中增加了对多字段搜索的支持 https://github.com/twitter/typeahead.js/pull/811

    用法:
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('title', 'description'),