4

默認情況下,typeahead plugin利用單個數據源來獲取結果。我想是因爲它到多個領域內進行搜索,因此,如果說,我有:在多個字段中製作Twitter Bootstrap的typead搜索

var items = [ 
    {'title': 'Acceptable', 'description': 'Good, but not great'} 
] 

這將在titledescription領域都,最好通過AJAX搜索。

這個插件可以嗎?

+0

您可以輕鬆地通過傳遞選項自定義一個覆蓋'matcher'回調。 AJAX功能可以通過創建一個'source'回調來添加 – Phil

回答

2

Typeahead不支持不經過兩次調整就使用JSON對象。在Github有很少的pull請求,我有submitted one myself,但是,目前,您必須手動覆蓋selectrender。此外,還必須覆蓋highlightermatchersorterupdater,但這些可以通過傳入前面的選項來完成。

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() { /* ... */ } 
     }); 
    } 
});