【问题标题】:jQuery Count/Length Typeahead RemotejQuery Count/Length Typeahead Remote
【发布时间】:2017-08-25 18:07:19
【问题描述】:

我有一个文本框,我通过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 将返回为 undefined。我尝试过states.index.datums.length,但也以undefined 的形式返回。

如何使用远程 twitter typeahead 获得 lengthcountstates

【问题讨论】:

    标签: javascript jquery count twitter-typeahead bloodhound


    【解决方案1】:

    正如@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 运行后返回的状态数。 我从这篇文章中得到了信息: Typeahead.js - Show that there are more results

    【讨论】:

      【解决方案2】:

      那是因为我猜你的 state.length 是在 API 调用之前执行的。虽然从未实施过猎犬!只是猜测它发生在 jQuery ajax 请求中,我们必须在回调函数中处理输出数据,当访问它返回未定义时。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 2011-10-02
        相关资源
        最近更新 更多