Twitter Typeahead.js:点击/聚焦时显示所有选项

Twitter Typeahead.js: show all options when click/focus

本文关键字:显示 选项 聚焦 Typeahead js 点击 Twitter      更新时间:2023-09-26

我在自动完成文本输入中使用Typeahead.js,这很棒。但是当输入获得焦点时,我需要激活包含所有可用选项的下拉菜单。我见过的每个可能的解决方案都涉及使用某个值初始化输入,但我需要显示所有选项。

我怎样才能做到这一点?

任何说"minLength: 0 就是你所需要的"的答案都是不正确的。

"开箱即用" Typeahead v0.11.1 "确实需要" minLength 设置为 0,但如果您使用的是开箱即用的寻血猎犬引擎,那么您需要确保设置

identify: function(obj) { return obj.team; },

在你的寻血猎犬物体上。

你还需要一个"中间人"函数来处理你的"空查询",这是你将告诉寻血猎犬合作的地方。

function nflTeamsWithDefaults(q, sync) {
  if (q === '') {
    sync(nflTeams.all()); // This is the only change needed to get 'ALL' items as the defaults
  } else {
    nflTeams.search(q, sync);
  }
}

您可以在此处查看完整示例。

var nflTeams = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  identify: function(obj) { return obj.team; },
  prefetch: '../data/nfl.json'
});
function nflTeamsWithDefaults(q, sync) {
  if (q === '') {
    sync(nflTeams.all()); // This is the only change needed to get 'ALL' items as the defaults
  }
  else {
    nflTeams.search(q, sync);
  }
}
$('#default-suggestions .typeahead').typeahead({
  minLength: 0,
  highlight: true
},
{
  name: 'nfl-teams',
  display: 'team',
  source: nflTeamsWithDefaults
});

更具体地说,您可以在以下地址看到官方TWITTER TYPEAHEAD默认建议焦点示例,从.GET()到.ALL()的简单更改(见上文或下文)

http://twitter.github.io/typeahead.js/examples/#default-suggestions

。希望这对某人有所帮助,因为我花了一些时间才能找到这些信息(通过遵循所有错误报告并尝试查找 .all() 方法找到它)......

您需要

使用选项minLength: 0

注意:

有一个拉取请求解决了这个问题

我对 10.2 进行了快速修改,使此处找到的"基础知识"示例显示在焦点上。

我将 MIXIN _onFocus(第 1459 行)从:

_onFocused: function onFocused() {
    this.isActivated = true;
    this.dropdown.open();
},

自:

_onFocused: function onFocused() {
    this.isActivated = true;
    var val = this.input.getInputValue(); 
    var query = Input.normalizeQuery(val);
    this.dropdown.update(query);
    this.dropdown.open();
},

这几乎不是官方的,但它完成了工作。

使用 0.10.4

要返回空白查询的所有结果,请在猎犬的第 450 行添加以下内容.js

     if (query == "") { return that.datums; }

在焦点上触发匹配 在焦点时触发输入上的按键按下事件

     $(input_element).on("click", function () {
        ev = $.Event("keydown")
        ev.keyCode = ev.which = 40
        $(this).trigger(ev)
        return true
    });

现在有一种方法可以做到这一点,而不必修改预先键入源文件。您必须做两件事 - 将最小长度设置为 0,并为焦点事件添加事件处理程序:在下面的例子中,我从Twitter页面(https://twitter.github.io/typeahead.js/examples/)上的第一个例子中复制了 - 确保输入的位置.js和jquery-ui.js是正确的。

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="typeahead.js"></script>
<script src="jquery-ui.js"></script>
   <script>
   $(function(){
var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substrRegex;
    // an array that will be populated with substring matches
    matches = [];
    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');
    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        // the typeahead jQuery plugin expects suggestions to a
        // JavaScript object, refer to typeahead docs for more info
        matches.push({ value: str });
      }
    });
    cb(matches);
  };
};
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
  'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
  'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
  'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
  'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
  'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
  'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
  'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
  'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];
$('.typeahead').typeahead({
  hint: true,
  highlight: true,
  minLength: 0
},
{
  name: 'states',
  displayKey: 'value',
  source: substringMatcher(states)
});
 $('.typeahead').on( 'focus', function() {
          if($(this).val() === '') // you can also check for minLength
              $(this).data().ttTypeahead.input.trigger('queryChanged', '');
      });
});
   </script>
    </head>
<body>
  <input class="typeahead" type="text" placeholder="States of USA">
</div>
</body>
</html>

已验证这适用于 0.10.5。注意:发现这不适用于寻血猎犬搜索引擎,因为寻血猎犬的查询令牌器需要一个字符。

现在有一种更简单的方法可以在不修改源的情况下执行此操作。可能是自从最初回答这个问题以来,来源已经发生了变化,但我认为值得放在这里以防万一。

创建预类型后:

var $element = $('#myTextElement');
$element.typeahead({ source: ['Billy', 'Brenda', 'Brian', 'Bobby'] });

只需将最小长度设置为 0:

$element.data('typeahead').options.minLength = 0;

创建预类型时,minLength 选项强制为 1,但您可以在创建后对其进行设置,并且它可以完美运行。

在 typeahead v.0.11.1 中,已应用其他答案中引用的修补程序。您可以使用以下选项实现此目的:

minLength: 0

适用于键盘或鼠标焦点。无需更改代码或新事件。

实现此行为的最简单方法是将 minLinegth 设置为零并设置预取属性。相反,要设置本地 JSON 源,只需放置没有查询参数的搜索 url:

let baseUrl = 'some-url.com',
    url = baseUrl + '?search=%QUERY';
...
$el.typeahead({
    minLength: 0,
    highlight: true,
    prefetch: baseUrl
}, {
    ...
});

另一种选择是使用 Typeahead 的非公共 API。 完整的Typeahead对象可以通过jQuery的data方法获得。

var _typeaheadElem = $('#myInput').find('.typeahead');
var _typeahead = _typeaheadElem.data('ttTypeahead');
_typeaheadElem.focus(function() {
    /* WARNING: This is hackery abusing non-public Typeahead APIs */
    if (_typeaheadElem.val() === "") {
        var input = _typeahead.input; //Reference to the TA Input class
        //Set the component's current query to something !== input.
        input.query = "Recent People";
        input._onInput("");
    }
});

查看适用于 v0.10.2 的更多代码http://pastebin.com/adWHFupF

这与 PR 719 相关联https://github.com/twitter/typeahead.js/pull/719