是否可以使用自定义分隔符将两个源添加到 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/