如何禁用typeahead:在远程typeahead.js中聚焦已填充的文本字段时处于活动状态

how to disable typeahead:active when focusing a filled-in text field in a remote typeahead.js

本文关键字:typeahead 文本 字段 填充 活动状态 聚焦 何禁用 js      更新时间:2024-03-09

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

typeahead.js在聚焦文本字段时似乎总是显示菜单。这是有道理的,因为minLength是2,文本字段值类似于"Tony"(或其他什么)。但我尝试过在typeahead:active事件的回调中使用hint: false和调用$('.typeahead').typeahead('close'),但这两种方法似乎都无法阻止菜单的显示。

这是我正在使用的init代码:

$('#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>');
        }
    }
});

在我聚焦文本字段和实际显示菜单之间有一个轻微的延迟,因为必须运行远程GET。所以我想我需要在集中注意力之后,以某种方式防止这种情况发生。

似乎关闭typeahead:open事件中的菜单就可以了,但这对我来说似乎很糟糕

$('#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);
});

如果有人知道更好的方法,我洗耳恭听!