如何在远程 typeahead.js 中聚焦填充文本字段时禁用 typeahead:active

tab*_*ber 1 javascript typeahead.js twitter-typeahead

我正在使用 typeahead.js,它很棒,但这是我的用例:我有一个文本字段,当页面加载时,它已经在服务器端填充了一个字符串,所以我不希望建议菜单成为当用户聚焦文本字段时显示。

typeahead.js在聚焦文本字段时似乎总是显示菜单。这是有道理的,因为它minLength是 2 并且文本字段值类似于“Tony”(或其他)。但是我已经尝试在事件的回调中使用hint: false和调用,并且似乎都没有停止显示菜单。$('.typeahead').typeahead('close')typeahead:active

这是我正在使用的初始化代码:

$('#locationInput').typeahead({
    hint: false,
    highlight: false,
    minLength: 2
},
{
    name: 'locations',
    display: 'name',
    source: typeaheadLocations, // a simple Bloodhound instance
    templates: {
        suggestion: function(locationObj) {
            return $('<div>' + locationObj.name + '</div>');
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

还有就是当我焦点的文本字段,菜单实际显示,因为远程GET已运行之间有轻微的延迟。所以我猜我需要以某种方式阻止它,在它集中之后。

tab*_*ber 5

看起来在typeahead:open事件中关闭菜单可以解决问题,但这对我来说似乎很hack-ish。:(

$('#locationInput').typeahead({
    hint: true,
    highlight: true,
    minLength: 2
},
{
    name: 'locations',
    display: 'name',
    source: typeaheadLocations,
    templates: {
        suggestion: function suggestion(locationObj) {
            return $('<div>' + locationObj.name + '</div>');
        }
    }

}).on('typeahead:open', function(e) {
    var $input = $(e.currentTarget);

    if (!$input.data('wasFocusedOnce')) {
        $input.data('wasFocusedOnce', true);
        $input.typeahead('close');
    }

}).on('typeahead:close', function(e) {
    $(e.currentTarget).removeData('wasFocusedOnce');
}).on('keydown', function(e) {
    $(e.currentTarget).data('wasFocusedOnce', true);
});
Run Code Online (Sandbox Code Playgroud)

如果有人知道更好的方法来做到这一点,我全神贯注!

  • @TimScarborough 实际上是 2019 年:D (2认同)
  • 伙计们!你不知道我在 2020 年看到这个有多高兴!!! (2认同)