提前输入两个源和自定义分隔符

Bootstrap's Typeahead with two sources and custom separator

本文关键字:两个 自定义 分隔符 输入      更新时间:2023-09-26

是否可以添加两个源到Bootstrap Typeahead与自定义分隔符?

目前我有

source: function (query, process) {
    ...
       process(data.names.merge(data.areas));
    ...
}

然而,我非常想在两者的结果之间添加自定义HTML。现在它们在显示时也混合在一起,我希望它们在两个单独的列表中,使用自定义HTML作为分隔符。

有可能吗?

答案是肯定的。您将需要知道分隔符应该出现在组合列表中的哪个位置,该列表将被缩小到与用户输入的"查询"(this.query)匹配的位置。

您可以通过覆盖render方法来更改生成的HTML,这需要直接访问typeahead对象来完成:

var typeahead = $("#myTypeahead").typeahead(/* ... */).data('typeahead');
typeahead.render = function(items) {
    var that = this
    // this "map"s the items, which iterates over them and generates a new
    //  li for each item _by default_; I have modified it
    items = $(items).map(function (i, item) {
        // return an array containing raw HTML Elements
        var elements = []
        // determine if separator is necessary, but make sure that it
        //  is not the first li (which this would be if it matched the
        //  i === 0 item!)
        if (item === "worthSeparating") {
            // put whatever you want as the separator in the elements array,
            //  which will appear in the position that you return it
            //  you probably don't want text, rather you want some CSS class
            elements.push($("<li/>").addClass("menu-separator")[0])
        }
        // ordinary li that is displayed:
        i = $(that.options.item).attr('data-value', item)
        i.find('a').html(that.highlighter(item))
        elements.push(i[0])
        return elements
    });
    items.first().addClass('active')
    this.$menu.html(items)
    return this
};

上面的render方法是由默认方法修改的。你对发生的事情有完全的控制权。事实上,如果您不喜欢默认菜单,那么您可以通过传递默认提供的不同选项来转换菜单:

{
    menu: '<ul class="typeahead dropdown-menu"></ul>',
    item: '<li><a href="#"></a></li>'
}

更改这些需要对render方法进行不同的更改。