我无法在此处找到默认的Twitter typeahead自定义模板:http://twitter.github.io/typeahead.js/examples/#custom-templates 我能够让默认的演示工作得很好。 这是我的js代码
jQuery(document).ready(function() {
var bestPictures = [
{"year": "1996", "value": "Tom", "url": "http://example.com"},
{"year": "1998", "value": "Tim", "url": "http://example.com"}
];
$('#custom-templates .typeahead').typeahead(null, {
name: 'best-pictures',
display: 'value',
source: bestPictures,
templates: {
empty: [
'<div class="empty-message">',
'unable to find any Best Picture winners that match the current query',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<div><strong>{{value}}</strong> – {{year}}</div>')
}
});
});
我找不到示例的源代码,因为它们来自bestPictures
。我也安装了把手。当我在搜索框中输入字母t
时,我的控制台日志在此行的this.source is not a function
中显示typeahead.bundle.js
:this.source(query, sync, async);
此外,我想在选择下拉选项后进行重定向,类似于
on('typeahead:selected', function(event, datum) {
window.location = datum.url
});
答案 0 :(得分:0)
尝试使用Bloodhound
,将对象bestPictures
作为可在.typeahead
suggestions
函数
jQuery(document).ready(function() {
var bestPictures = [{
"year": "1996",
"value": "Tom",
"url": "http://example.com"
}, {
"year": "1998",
"value": "Tim",
"url": "http://example.com"
}];
var pictures = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: $.map(bestPictures, function(d) {
return {
value: d.value,
// pass `bestPictures` to `suggestion`
suggest: d
}
})
});
pictures.initialize();
$("#custom-templates .typeahead").typeahead(null, {
name: "best-pictures",
display: "value",
source: pictures.ttAdapter(),
templates: {
notFound: [
"<div class=empty-message>",
"unable to find any Best Picture winners that match the current query",
"</div>"
].join("\n"),
suggestion: function(data) {
// `data` : `suggest` property of object passed at `Bloodhound`
return "<div><strong>" + data.suggest.value + "</strong>"
+ data.suggest.year + "</div>"
}
}
});
});
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js">
</script>
<div id="custom-templates">
<input type="text" class="typeahead" placeholder="Best picture winners" />
</div>