更改下拉列表的外观非常简单,因为前面的答案建议您应该将自定义样式添加到 Bootstrap CSS 之后包含的文件中,以确定您需要使用哪些选择器来覆盖 Bootstrap 的样式我建议您使用浏览器的DOM 检查工具。
现在棘手的部分是在结果末尾添加自定义链接,我注意到将项目附加到结果数组的最佳位置是在函数的开头,render
因为这个函数不像sorter
在数组被切片后调用选项中设置的最大项目数,render
无法使用插件选项进行配置,因此您需要进行“手动”覆盖:
$('input').typeahead().data('typeahead').render = function (items) {
var that = this
items.push('View All'); //Append "View All option"
//The rest is the default render function taken from bootstrap's js source
items = $(items).map(function (i, item) {
i = $(that.options.item).attr('data-value', item)
i.find('a').html(that.highlighter(item))
return i[0]
})
items.first().addClass('active')
this.$menu.html(items)
return this
};
然后为了防止链接在用户类型时突出显示,您需要自定义默认highlighter
功能:
highlighter: function (item) {
//If it's our link than just return the text in bold
if (item == 'View All')
return '<strong>' + item + '</strong>'
//The rest is the default hightlighter function taken from bootstrap's js source
var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>'
});
}
最后,为了处理对自定义链接的点击,我们需要实现一个updater
函数,以便在选择下拉列表中的选项时调用
updater:function(item){
if(item == 'View All'){
//Handle click on our link
window.location = 'http://example.com/search?q=' + this.$element.val();
}
return item;
}
您可以查看此小提琴以获取完整的工作示例