【问题标题】:Twitter Typeahead/Bloodhound Suggestions from Ajax-Source: how manage multiple values?来自 Ajax-Source 的 Twitter Typeahead/Bloodhound 建议:如何管理多个值?
【发布时间】:2016-04-13 11:27:36
【问题描述】:

我正在使用 typeahead/bloodhound 来获取来自 ajax 源的建议:

var protags = new Bloodhound({  
datumTokenizer: function(protags) {
return Bloodhound.tokenizers.whitespace(protags.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/ajax/getinfo.php?q=%QUERY',
wildcard: '%QUERY',
filter: function(response) {     
return response.protags;
}
}
});

getinfo.php 的 JSON 结果如下所示:

{
"protags": [
{"tag": {
"tagid": "1",
"tagtitle": "titleone"}
},
{"tag": {
"tagid": "2",
"tagtitle": "titletwo"}
},
{"tag": {
"tagid": "3",
"tagtitle": "titlethree"}
}]}

我能够检索我想要的所有信息(tagtitle 和 tagid)并使用以下方式显示它:

$('.typeahead').typeahead(
{ hint: true,
highlight: true,
minLength: 1
}, 
{
name: 'protags',
displayKey: function(protags) {
return protags.tag.tagtitle+'-'+protags.tag.tagid;
},
source: protags.ttAdapter()
});

但我对此感到困惑:我如何才能在建议字段中仅显示标签标题,但同时获取 protags.tag.tagid 以进行更多服务器端操作?

【问题讨论】:

  • 用户选择后是否要使用数据?
  • yeezzz:是的,这正是我想要的
  • 试试我的答案...我忘记了建议字段,所以我会在一分钟内编辑
  • 对不起,但我不能让它在我的预输入块中工作:-(
  • 好吧,也许你可以发一个小提琴?

标签: javascript typeahead.js typeahead bloodhound


【解决方案1】:

使用 :select 事件 (v 0.11.x) 或 :selected 事件 (v.0.10.x)。阅读 Bloodhound/typeahead 文档,因为他们在 0.10.x 和 0.11.x 之间进行了很多更改

我使用的是 0.10.5,就我而言,它看起来像这样:

编辑:查看您的 json,我不确定模板和 :selected 函数中有哪些数据。您可能需要使用 data.protags.tag 等

$(selector).typeahead(
    // options, key, source etc

    templates: {
        suggestion: function (data) {
            return '<div class="tt-name">' + data.tag.tagtitle + '</div>';
        }
    }
    // end of options
)
.on('typeahead:selected',
    function(event, data) {
    // you should be able to get your data here, if I'm correct like so:
    console.log(data.tag.tagid);
   }
);

【讨论】:

  • 大家,请注意您的预输入版本,就像上面提到的 yeezzz 一样! .on('typeahead:selected' 与 .on('typeahead:select'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多