在多个字段中进行Twitter Bootstrap的typead搜索 [英] Make Twitter Bootstrap's typead search within multiple fields
问题描述
默认情况下,预先输入插件使用单个数据源为了获取结果。我想要它在多个字段中搜索,所以如果说,我有:
By default, the typeahead plugin makes use of a single data source in order to fetch the results. What I would like is for it to search within multiple fields, so if say, I have:
var items = [
{'title': 'Acceptable', 'description': 'Good, but not great'}
]
它将搜索 title
和 description
字段,最好是通过AJAX。
It will search on both the title
and description
fields, ideally via AJAX.
这个插件有可能吗?
推荐答案
Typeahead不支持使用没有两个调整的JSON对象。 Github中有很少的拉取请求,我有自己提交,但是,目前,您必须手动覆盖选择
和渲染
。此外,您还必须覆盖荧光笔
,匹配器
,分拣机
,和更新程序
,但这些可以通过传递到预先输入的选项完成。
Typeahead does not support using JSON objects without two tweaks. There are few pull-requests in Github for this, and I have submitted one myself, but, currently, you must manually override select
and render
. Additionally, you must also override highlighter
, matcher
, sorter
, and updater
, but those can done via the options passed into the typeahead.
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
};
如果您需要其他人的帮助,请告诉我,但要点是:
If you need help with the other ones, then let me know, but the gist of it is:
control.typehead({
matcher: function (item) {
var lcQuery = this.query.toLowerCase();
return ~item.title.toLowerCase().indexOf(lcQuery)
|| ~item.description.toLowerCase().indexOf(lcQuery);
}
};
我还有 JFiddle示例与我提出的pull请求有关,但2.3.1中没有排序函数,甚至没有接受pull请求的3.x所以你必须完全覆盖 sorter
才能有效地重复上面用 matcher
做的事情(在排序时检查两者) )。
I also have a JFiddle example related to the pull request that I made, but the sorting functions do not exist in 2.3.1, or even 3.x without the pull request being accepted, so you will have to override sorter
in its entirety to effectively repeat what I did with matcher
above (checking both while sorting).
对于AJAX调用,您可以在传入的选项中覆盖源
方法以获取AJAX功能。不返回 sou rce
调用,它假定第二个参数 process,
将被调用结果。
As for the AJAX call, you can override the source
method in the passed in options to get AJAX functionality. By not returning to the source
call, it assumes that the second parameter, process,
will be invoked with results.
control.typehead({
minLength: 3,
source: function(query, process) {
$.ajax({
url: url + encodeURIComponent(query),
type: 'GET',
success: process,
error: function() { /* ... */ }
});
}
});
这篇关于在多个字段中进行Twitter Bootstrap的typead搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!