问题
I am having trouble getting the default Twitter typeahead custom template working found here: http://twitter.github.io/typeahead.js/examples/#custom-templates I am able to get the default demo working just fine. Here is my js code
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>')
}
});
});
I couldn't find the source code of the example in where they get bestPictures
from. I also have handlebars installed. When I type in the letter t
into the search box, my console log shows this.source is not a function
in typeahead.bundle.js
on this line: this.source(query, sync, async);
Additionally, I would like to do a redirect once a dropdown option is selected, similar to
on('typeahead:selected', function(event, datum) {
window.location = datum.url
});
回答1:
Try using Bloodhound
, returning object bestPictures
as a property accessible at .typeahead
suggestions
function
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>
来源:https://stackoverflow.com/questions/35074983/twiiter-typeahead-custom-templates-getting-default-example-working