默認情況下,typeahead plugin利用單個數據源來獲取結果。我想是因爲它到多個領域內進行搜索,因此,如果說,我有:在多個字段中製作Twitter Bootstrap的typead搜索
var items = [
{'title': 'Acceptable', 'description': 'Good, but not great'}
]
這將在title
和description
領域都,最好通過AJAX搜索。
這個插件可以嗎?
默認情況下,typeahead plugin利用單個數據源來獲取結果。我想是因爲它到多個領域內進行搜索,因此,如果說,我有:在多個字段中製作Twitter Bootstrap的typead搜索
var items = [
{'title': 'Acceptable', 'description': 'Good, but not great'}
]
這將在title
和description
領域都,最好通過AJAX搜索。
這個插件可以嗎?
Typeahead不支持不經過兩次調整就使用JSON對象。在Github有很少的pull請求,我有submitted one myself,但是,目前,您必須手動覆蓋select
和render
。此外,還必須覆蓋highlighter
,matcher
,sorter
和updater
,但這些可以通過傳入前面的選項來完成。
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中不存在排序功能,因此您必須覆蓋sorter
的全部內容,纔能有效地重複我對上面的matcher
所做的操作(在排序時檢查兩者)。
至於AJAX調用,您可以在傳入選項中覆蓋source
方法以獲取AJAX功能。通過不返回source
調用,它假定第二個參數process,
將與結果一起被調用。
control.typehead({
minLength: 3,
source: function(query, process) {
$.ajax({
url: url + encodeURIComponent(query),
type: 'GET',
success: process,
error: function() { /* ... */ }
});
}
});
加入事先鍵入的內容爲多個領域的支持搜索在10.3 https://github.com/twitter/typeahead.js/pull/811
用法:
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('title', 'description'),
您可以輕鬆地通過傳遞選項自定義一個覆蓋'matcher'回調。 AJAX功能可以通過創建一個'source'回調來添加 – Phil