jQuery Count/Length Typeahead 遥控器

jQuery Count/Length Typeahead Remote

我有一个文本框,我在其中通过 Twitter Typeahead 使用自动完成功能,特别是远程示例。

这是我的代码:

var states = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('state'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: getStateUrl + "?query=%QUERY",
        wildcard: '%QUERY'
    }
});

var sLength = states.length; // this comes back as undefined

$('#StateName').typeahead({
    highlight: true
}, {
    name: 'states',
    display: 'state',
    source: states,
    limit: 10
}).bind('typeahead:select', function(ev, suggestion) {
    $("#StateId").val(suggestion.id);
});

如果您没有在我的代码中看到注释,states.length returns as undefined。我试过 states.index.datums.length,但结果也是 undefined

如何使用远程 Twitter 预先输入来获取 stateslengthcount

那是因为我猜你的 state.length 在 API 调用之前被执行了。虽然从未实施过猎犬!只是猜测因为它发生在 jQuery ajax 请求中,当从它 returns undefined.

中访问时,我们将不得不在回调函数中处理输出数据

正如@Sai-nihar-nightraiser 所说,您试图在收集结果之前设置结果的长度。 像这样尝试:

var sLength;

var states = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('state'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
    url: getStateUrl + "?query=%QUERY",
    wildcard: '%QUERY',
    filter: function (statesResults){
        window.sLength = statesResults.length;
        return statesResults;
  }
});

sLength 应等于 typeahead 后返回的状态数 运行。 我从这个 post 得到了信息: Typeahead.js - Show that there are more results