30

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

我怎么能做到这一点?

4

9 回答 9

26

任何说“minLength: 0 is all you need”的答案都是不正确的。

“开箱即用”Typeahead v0.11.1 '确实需要' minLength 设置为 0,但如果您使用的是开箱即​​用的 Bloodhound 引擎,那么您需要确保设置

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

在你的猎犬对象上..

您还需要一个“中间人”功能来处理您的“空查询”,这是您将告诉 Bloodhound 合作的地方。

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 预先输入的默认建议焦点示例,从 .get() 到 .all() 的简单更改(见上文或下文)

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

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

于 2015-09-27T21:00:55.697 回答
14

您需要使用该选项minLength: 0

笔记:

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

于 2013-11-07T11:24:49.040 回答
11

我对 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();
},

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

于 2014-07-09T23:31:14.583 回答
3

使用 0.10.4

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

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

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

     $(input_element).on("click", function () {
        ev = $.Event("keydown")
        ev.keyCode = ev.which = 40
        $(this).trigger(ev)
        return true
    });
于 2014-09-17T13:52:19.210 回答
3

现在有一种方法可以做到这一点,而无需修改预先输入的源文件。您必须做两件事 - 将 minlength 设置为 0 并为焦点事件添加一个事件处理程序:在下面的示例中,我从 Twitter 页面上的第一个示例中复制(https://twitter.github.io/typeahead. js/examples/ ) - 确保 typeahead.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。注意:发现这不适用于 Bloodhound 搜索引擎,因为 Bloodhound 的 queryTokenizer 需要一个字符。

于 2015-02-17T00:13:26.650 回答
2

现在有一种更简单的方法可以做到这一点,而无需修改源代码。自从最初回答这个问题以来,可能是来源已经改变,但我认为值得把它放在这里以防万一。

创建预输入后:

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

只需将 minLength 设置为 0:

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

创建预输入时,minLength 选项被强制为 1,但您可以在创建后设置它并且它工作得很好。

于 2014-08-22T09:40:17.017 回答
1

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

minLength: 0

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

于 2015-05-22T01:57:20.840 回答
1

我实现此行为的最简单方法是将 minLinegth 设置为零并设置 prefetch 属性。而不是设置本地 JSON 源,只需放置不带查询参数的搜索 url:

let baseUrl = 'some-url.com',
    url = baseUrl + '?search=%QUERY';

...

$el.typeahead({
    minLength: 0,
    highlight: true,
    prefetch: baseUrl
}, {
    ...
});
于 2021-05-20T15:15:00.450 回答
0

另一种选择是使用 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

于 2014-05-08T19:54:23.170 回答