小编典典

TypeAhead.js和Bloodhound显示奇数结果

json

我的前端有一个TypeAhead / Bloodhound实现,可从Play /
Scala服务器获取JSON数据。Typeahead版本为0.11.1。实现如下:

HTML:

<div id="typeahead" class="col-md-8">
   <input class="typeahead form-control"  type="text" placeholder="Select the user">
</div>

JavaScript:

var engine = new Bloodhound({
  datumTokenizer: function (datum) {
    var fullName = fullName(datum);
    return Bloodhound.tokenizers.whitespace(fullName);
  },
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  identify: function(obj) { return obj.id; },
  remote: {
    url: routes.controllers.Users.index("").url,
    cache: false,
    replace: function (url, query) {
        if (!isEmpty(query)) {
            url += encodeURIComponent(query);
        }
        return url;
    },
    filter: function (data) {
        console.log(data);
        return $.map(data, function (user) {
            return {
                id: user.id,
                fullName: viewModel.fullName(user)
            };
        });
    }
}
});

// instantiate the typeahead UI
$('#typeahead .typeahead')
.typeahead({
    hint: true,
    highlight: true,
    minLength: 1,
},
{
    name: 'engine',
    displayKey: 'fullName',
    source: engine
})

function fullName(data) {
  if (data === undefined) return "";
  else {
    var fName = data.firstName === undefined ? "" : data.firstName;
    var lName = data.lastName === undefined ? "" : data.lastName;
    return fName + ' ' + lName;
  }
};

服务器提供的JSON响应:

[{"firstName":"Test","lastName":"User", "id":1}, ... ]

服务器分页结果,以便最多给出5个结果,这也应该是Typeahead / Bloodhound的默认限制。

问题在于,当服务器返回5个结果时,Typeahead在叠加层中显示0个结果。如果服务器给出4个结果,则TypeAhead在覆盖中显示1。如果服务器给出3个结果,则TypeAhead显示2个结果。对于2和1的结果,它会显示叠加层中正确数量的元素。如果删除页面长度,并且服务器返回超过10个结果,则TypeAhead将显示5个结果(限制)。过滤器中的console.log显示正确的数据结果数,因此它们至少进入了Bloodhound。

此代码可能是什么问题?此TypeAhead字段是此页面中存在的唯一TypeAhead字段。我检查了DOM,TypeAhead生成了错误数量的结果集字段,因此CSS没问题(也试图删除所有自定义CSS)。

感谢您的任何答复:)


阅读 266

收藏
2020-07-27

共1个答案

小编典典

代码中的提前输入存在问题:

https://github.com/twitter/typeahead.js/issues/1218

您可以按照问题页面上的说明,自己在JS中更改代码。

2020-07-27