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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19797370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:49:54  来源:igfitidea点击:

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

javascripttwitter-bootstrap-3typeahead.js

提问by César García Tapia

I'm using Typeahead.js in an autocomplete text input, and it's great. But I need to activate the dropdown menu with all the available options when the input gets focus. Every possible solution I've seen involves initializing the input with some value, but I need to show allthe options.

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

How could I achieve this?

我怎么能做到这一点?

采纳答案by César García Tapia

You need to use the option minLength: 0

您需要使用该选项 minLength: 0

Note:

笔记:

There's a pull requestwhich solved this issue

有一个pull request解决了这个问题

回答by NinjaKC

Any answer that says "minLength: 0 is all you need", is NOT TRUE.

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

"Out Of The Box" Typeahead v0.11.1 'does need' minLength set to 0, but ALSO if you are using the out of the box Bloodhound Engine, then you need to be sure to set

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

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

on your Bloodhound Object..

在你的 Bloodhound 对象上..

You also need a "middle man" function to handle your "empty query", which is where you will tell Bloodhound to cooperate..

您还需要一个“中间人”功能来处理您的“空查询”,这是您告诉 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);
  }
}

You can see the FULL EXAMPLE here..

你可以在这里看到完整的例子..

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
});

MORE SPECIFICALLY YOU CAN SEE THE OFFICIAL TWITTER TYPEAHEAD DEFAULT SUGGESTION ON FOCUS EXAMPLE AT THE FOLLOWING ADDRESS, WITH THE SIMPLE CHANGE FROM .get() TO .all() (SEE ABOVE OR BELOW)

更具体地说,您可以在以下地址看到官方推特预先输入的关于焦点示例的默认建议,只需将 .get() 更改为 .all()(见上文或下文)

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

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

... hope this helps someone, as it took me some time to find this information (found it by following all the bug reports & experimenting to find .all() method) ...

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

回答by Scottie

I made a quick modification to 10.2 that made "the basics" example found heredisplay on focus.

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

i changed the mixin _onFocus (line 1459) FROM:

我更改了 mixin _onFocus(第 1459 行)来自:

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

TO:

到:

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

It's hardly official but it got the job done.

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

回答by Josh Dean

Using 0.10.4

使用 0.10.4

To return all results for blank query add the following at line 450 of bloodhound.js

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

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

To trigger the match on focus trigger the key down event on your input when focused

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

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

回答by vanval

There is a way to do this now without having to modify the typeahead source file. You have to do two things - set minlength to 0 and also add an event handler for the focus event: In the below example which I copied from the first example on the Twitter page (https://twitter.github.io/typeahead.js/examples/) - make sure the location to typeahead.js and jquery-ui.js is correct.

现在有一种方法可以做到这一点,而无需修改预先输入的源文件。您必须做两件事 - 将 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>

Verified this works with 0.10.5. Note: Found this does not work with the Bloodhound search engine since the queryTokenizer for Bloodhound expects a character.

验证这适用于 0.10.5。注意:发现这不适用于 Bloodhound 搜索引擎,因为 Bloodhound 的 queryTokenizer 需要一个字符。

回答by Robert

There's an easier way to do this now without modifying the source. It might be that the source has changed since this was originally answered, but I thought it worth putting here just in case.

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

After creating the typeahead:

创建预先输入后:

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

Simply set the minLength to 0:

只需将 minLength 设置为 0:

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

The minLength options is forced to 1 when the typeahead is created, but you can set it after creation and it works perfectly.

创建预先输入时, minLength 选项强制为 1,但您可以在创建后设置它,它可以完美运行。

回答by Jonathan Lidbeck

In typeahead v.0.11.1, the patch referenced in other answers has been applied. You can achieve this with the option:

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

minLength: 0

minLength: 0

Works on keyboard or mouse focus. No code changes or new events needed.

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

回答by Snekse

Another option is to use the non-public APIs of Typeahead. The full Typeahead object is available through jQuery's datamethod.

另一种选择是使用 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("");
    }
});

See more code that works in v0.10.2 http://pastebin.com/adWHFupF

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

This is linked to PR 719 https://github.com/twitter/typeahead.js/pull/719

这链接到 PR 719 https://github.com/twitter/typeahead.js/pull/719