我在获取此处找到的默认 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
的位置找到该示例的源代码。我还安装了 Handlebars 。当我在搜索框中输入字母 t
时,我的控制台日志显示 typeahead.bundle.js
中的 this.source 不是函数
在这一行:this.source(query,sync,async);
此外,我想在选择下拉选项后进行重定向,类似于
on('typeahead:selected', function(event, datum) {
window.location = datum.url
});
最佳答案
尝试使用 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>
关于javascript - Twitter Typeahead 自定义模板 - 让默认示例正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35074983/