Jon*_*han 10 javascript jquery twitter-bootstrap
我正在玩Typeahead,我想弄清楚是否有办法在搜索查询中显示图片和标签?当我们尝试在Tweets上提及用户时,Twitter的做法.
Jon*_*han 14
在做了一些研究并几乎把我所有的头发拉出后,我终于想出了如何将Fullname,图像和用户名添加到像twitter这样的类型.
让我们说这是源的每个对象的以下结构,
{{ friend.id }}#{{ friend.username }}#{{ friend.imgurl }}#{{ friend.fullname }}
Run Code Online (Sandbox Code Playgroud)
然后你所要做的就是写一个漂亮的荧光笔,就像这样
highlighter: function(item) {
var parts = item.split('#'),
html = '<div class="typeahead">';
html += '<div class="media"><a class="pull-left" href="#"><img src='+parts[2]+' /></a>'
html += '<div class="media-body">';
html += '<p class="media-heading">'+parts[3]+' (@'+parts[1]+')'+'</p>';
html += '</div>';
html += '</div>';
return html;
},
Run Code Online (Sandbox Code Playgroud)
这将在Typeahead中轻松添加图片,全名和用户名.
您可能会发现使用http://ivaynberg.github.com/select2/更容易/更好,而不是尝试自定义默认垃圾Bootstrap!
如果你在该页面上搜索Templating,你会发现它 - 它看起来像这样:

荧光笔不再工作了.
使用模板,例如:
var my_friends = [
{name: "John", picture: "http://..."}
,{name: "Mel", picture: "http://..."}
];
var friends = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: my_friends
});
friends.initialize();
$('#friend_name').typeahead(
{
hint: true,
highlight: true,
minLength: 1,
},
{
name: 'friends',
displayKey: 'name',
source: friends.ttAdapter(),
templates: {
empty: 'not found', //optional
suggestion: function(el){return '<img src="'+el.picture+'" />'+el.name}
}
}
);
Run Code Online (Sandbox Code Playgroud)
资料来源:https://gist.github.com/jharding/9458780#file-custom-templates-js
小智 5
您可以尝试使用以下自定义代码来呈现包含JSON模式的图像.
预先输入看起来像:
$(".typeahead").typeahead({
source: function (query, process) {
//here we pass the query (search) and process callback arguments to the throttled function
throttledRequest(query, process);
},
highlighter: function (item) {
var test = testObjs[item];
return '<div class="test">' + '<img src="' + test.photo + '" />' + '<br/><strong>' + test.name + '</strong>' + '</div>';
},
updater: function (selectedName) {
//note that the "selectedName" has nothing to do with the markup provided
//by the highlighter function. It corresponds to the array of names
//that we sent from the source function.
//save the id value into the hidden field
$("#testId").val(testObjs[selectedName].id);
//return the string you want to go into the textbox (the name)
return selectedName;
}
});
Run Code Online (Sandbox Code Playgroud)