javascript - Bootstrap 的 Typeahead 有两个源和自定义分隔符

标签 javascript html twitter-bootstrap bootstrap-typeahead

是否可以使用自定义分隔符将两个源添加到 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 方法进行不同的更改。

关于javascript - Bootstrap 的 Typeahead 有两个源和自定义分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15159378/

相关文章:

javascript - 将输入插入数组并清除输入未按预期工作

javascript - Google Maps API 的哪些组件用于生成绘制许多地址的 map ?

javascript - Node.js: "process run out of memory"

html - CSS 覆盖 : Why Doesn't Search Box Float right?

java - 如何获取另一个类的元素之间的元素计数?

html - 当我使用自己的域在 gh-pages 上托管我的 jekyll 时,我的 CSS 根本不呈现

javascript - Node.JS + MySQL - 结合定义变量和选择数据的查询

css - Bootstrap 移动内联表单

javascript - Jquery Bootstrap 在点击时显示和隐藏跨度

html - Bootstrap 文件输入按钮没有改变