我正在使用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"}
}]}


我能够检索我想要的所有信息(标签标题和标签ID)并使用以下方法显示它:

$('.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?

最佳答案

使用: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);
   }
);

关于javascript - 来自Ajax的Twitter Typeahead/Bloodhound建议-来源:如何管理多个值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36596951/

10-11 06:01