【问题标题】:typeahead.js default select the first suggestiontypeahead.js 默认选择第一个建议
【发布时间】:2014-04-22 09:53:54
【问题描述】:

我正在使用 sifyion 的 angularJS 库进行 typeahead,它实际上使用 typeahead.js 和 Bloodhound.js 和 jquery。我有 typeahead.js v 0.10.2 和 jquery 1.10.2。 我的目标是创建一个搜索功能,用户只能从建议中进行选择。所以我已经实现了它,如果没有选择建议的结果,则提交带有 Null 参数的查询,否则提交建议。我已将选项设置为

minLength: 1,
hightlight: true,
editable: false

我有三个数据集,例如:

var bloodhoundStores = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
        url:'/url/param',
        filter: function(stores){
            return $.map(stores,function(store){return {name: store.name}})
        }
    }
});

我为所有这些调用清除缓存并在之后初始化它们,只是为了让你知道。我不是这方面的专家,但这样做可以解决我的目的

bloodhoundStores.clearPrefetchCache(); (on all three datasets)
.
bloodhoundStores.initialize(); (on all three datasets)

然后我将其设置为建议呈现,例如:

{
    name: 'Locality',
    displayKey: 'name',
    source: bloodhoundLocality.ttAdapter(), 
    templates:{
        header: '<h4 style="padding-bottom: 2px;"><i class="fa fa-location-arrow"></i>Locality</h4>',
        empty:['<p>','<span>No results found</span>','</p>'].join('\n'),
        suggestion: Handlebars.compile('<p><span class="sentence-case">{{name}}</span></p>')
    }
}

我的问题是,如果用户输入搜索词,我希望选择第一个建议(如果有的话)。我在 twitter typeahead.js github 存储库中查找了解决问题的解决方案。我一直无法想办法让他们为我工作。请帮助我或建议我以不同的方式实现它。

提前致谢

【问题讨论】:

  • 我也有一个问题,通常向右箭头会自动完成搜索查询,但如果用户按下键,它会显示下一个建议,光标位于末尾。右箭头键现在不会自动完成查询,用户必须再次按 Tab。建议我一些解决方法

标签: jquery angularjs typeahead.js twitter-typeahead bloodhound


【解决方案1】:

这是我的解决方案:

我有一个闭包,它封装了我的所有搜索表单逻辑,包括预输入源(和相关的)。看起来有点像这样:

(function() {
  var $searchBox,
      doSearch,
      firstMatch,
      searchResultHandler,
      typeaheadCallback,
      typeaheadSource;

  typeaheadSource = function(query, cb) {
    typeaheadCallback = cb;
    doSearch(query);
  };

  doSearch = function(term) {
    // Do some stuff here to query.
    // When the results come back, fire off a call to searchResultHandler.
  };

  searchResultHandler = function(response) {
    var data = JSON.parse(response.body); // I'm using sock.js in my app

    firstMatch = data[0].termToFillInSearchBox;

    if (typeaheadCallback) {
      typeaheadCallback(data);
    }
  };

  $searchBox.on("typeahead:closed", function(evt) {
    // Match what is in the search field against some expected pattern.
    // In my case, I'm looking for "Some Value.1234".
    // If the input doesn't match, and I have something in "firstMatch" then
    // substitute the value.
    if (! /\w+\.\d+/.test($searchBox.val()) && firstMatch !== undefined) {
      $searchBox.val(firstMatch);
      firstMatch = undefined;
    }
  });
}());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    相关资源
    最近更新 更多