Car*_*mba 48 javascript json twitter-typeahead
我已经有2天了,试图理解并清楚地了解如何使用/管理typeahead.js 0.10以便使用本地,远程和获取的数据.
老实说,对我来说,猎犬引擎并不清楚,有关如何操作/访问json对象和数组的详细信息仍然是一个问号.
我可以使本地示例工作,但任何时候我尝试使用预取或远程选项,除了几个滴答,我无法工作.
我在这篇文章中的目标不仅仅是找到我的问题的答案,而是找到一个完全了解它的人,并且能够以一种非常简单的方式逐步解释(使用examples/jsfiddles - 包括json示例,了解实际解析的内容)这个东西是如何工作的.
我想很多人都期待着理解它,这将是一个伟大的贡献(正如我们所知道的其他详细帖子).
我想这很辛苦.
在此先感谢您的贡献者.
遵循以下建议.我的简单例子.
JSON文件
[
{ "name": "Pink Floyd",
"Album": "The Best Of Pink Floyd: A Foot In The Door",
"Label": "EMI UK",
"Tracks":"Hey You, See Emily Play, The Happiest Days Of Our Lives, Another Brick in The Wall (Part 2), Have a cigar, Wish You Where Here, Time, The Great Gig in the Sky, Money, Comfortably Numb, High Hopes, Learning to Fly, The Fletcher Memorial Home, Shine On You Crazy Diamond, Brain Damage, Eclipse" ,
"Price": "16.40",
"Genre": "Rock"
},
{
"name": "Depeche Mode",
"Album": "A Question Of Time",
"Label": "Mute",
"Tracks":"A Question Of Time, Black Celebration, Something To Do, Stripped, More Than A Party, A Question Of Time(extended), Black Celebration" ,
"Price": "4.68" ,
"Genre": "Rock"
},
{
"name": "Placebo",
"Album": "Street Halo/Kindred",
"Label": "Hyperdub Japan",
"Tracks":"Street Halo, NYC, Stolen Dog, Kindred, Loner, Ashtray Wasp" ,
"Price": "14.06",
"Genre": "Future Garage"
}
]
Run Code Online (Sandbox Code Playgroud)
Typeahead脚本
<script>
var products = new Bloodhound({
datumTokenizer: function(d) {return d.name; },
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: 'http://localhost/dh/js/products.json'
});
products.initialize();
$('.test1').typeahead({
highlight: true
},
{
name: 'products',
displayKey: 'num',
source: states.ttAdapter()
});
</script>
Run Code Online (Sandbox Code Playgroud)
HTML
<script type="text/javascript" src="http://localhost/dh/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://localhost/dh/js/bootstrap.js"></script>
<script type="text/javascript" src="http://localhost/dh/js/typeahead.bundle.js"></script>
<div class="search_content">
<input class="test1" type="text" placeholder="product">
</div>
Run Code Online (Sandbox Code Playgroud)
小智 14
我只是花了几天时间试图让自己发挥作用,我完全同意它不直观.特别是在类型页面上有一件关于Bloodhound的事情尝试,因为我可能只是没有工作.例如以下行:
datumTokenizer:Bloodhound.tokenizers.obj.whitespace('value') - 总是会产生错误,因为obj不存在.
对于datumTokenizer,请使用以下格式(其中"DisplayText"是对象中包含将显示的文本的属性的名称):
function (d) {
return Bloodhound.tokenizers.whitespace(d.DisplayText);
}
Run Code Online (Sandbox Code Playgroud)
并记住在创建预先输入时将displayKey设置为集合中具有要显示的文本数据的属性的名称.对我而言,这总是与我想要标记的属性相同 - 所以我的先行语句如下所示:
$('#my-typeahead').typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'someName',
displayKey: 'DisplayText',
source: myBloodhound.ttAdapter()
}
Run Code Online (Sandbox Code Playgroud)