【问题标题】:Typeahead change sourceTypeahead 更改源
【发布时间】:2016-02-17 08:22:14
【问题描述】:

我正在尝试更改 typeahead 的来源,但我发现的所有答案都对我不起作用(可能是因为较新的引导程序版本)。我根据用户搜索的内容进行了后端搜索。这是我的代码:

$('.typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 1,
        limit: 2,
    },
    {
        name: 'organizations',
        source: substringMatcher(getOrganizationData())
    }).on("input", function(e) {
        organizationQuery = e.target.value;

        // Here I want to update the source

        // Not working:
        //$(".typeahead").data('typeahead').source = substringMatcher(getOrganizationData())

        // Not working:     
        //$('.typeahead').data('ttTypeahead').dropdown.datasets[0].source = substringMatcher(getOrganizationData())

        // Not working:
        // var autocomplete = $('input').typeahead();
        // autocomplete.data('typeahead').source = substringMatcher(getOrganizationData());
});

这是我的 getOrganizationData() 方法:

function getOrganizationData()
{
    var tempResults = [];
    $.getJSON( "search-organization?query="+organizationQuery, function( data ) {

        $.each(data, function (key, val) {
            var display = val.coc_number + ", " + val.name
            tempResults[key] = display;
            organizationHolder[display] = val.id;
        });

    });

    return tempResults;
}

如果我无法更新源,我应该如何根据我输入的内容查找结果?提前致谢!

【问题讨论】:

标签: jquery twitter-bootstrap typeahead.js typeahead


【解决方案1】:

AFAIK substringMatcher() 来自示例,它仅适用于字符串数组并且不需要 - 搜索在服务器端执行。此外,您不必响应用户输入,这是预先输入的工作。要将远程 JSON 查询用作 source,语法为:

source: function(query, sync, async) { .. }

其中syncasync 是回调。我猜你返回的 JSON 格式是

[ 
  { "name" : "qwerty" },
  { "name" : "another qwerty" },
  ... 
]

在使用 JSON 时,定义 displayKey 很重要,因此预输入知道它应该在下拉列表中显示哪个键/值属性。所以

$('.typeahead').typeahead(
    {
        hint: true,
        highlight: true,
        minLength: 1,
        limit: 2,
    },{
        name: 'organizations',
        displayKey: 'name', //example
        source: function(query, sync, async) {
           $.getJSON( "search-organization?query="+query, function( data ) {
              async(data);
           })
        })
    }
});

上面将自动显示带有突出显示的子字符串的预输入。确认在latest release上工作。

如果您想在预输入中显示一些其他值,即提到的val.coc_number + ", " + val.name,然后在调用async() 之前操作返回的 JSON:

data = data.map(function(item) { 
   item.numberName = item.coc_number + ", " + item.name;
   return item;
})

并相应地更改displayKey

displayKey: 'numberName', 

【讨论】:

  • 像魅力一样工作!真的很感激!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多