【问题标题】:how to disable typeahead:active when focusing a filled-in text field in a remote typeahead.js如何在远程 typeahead.js 中聚焦填充文本字段时禁用 typeahead:active
【发布时间】:2016-04-08 15:19:28
【问题描述】:

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

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

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

$('#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。所以我猜我需要以某种方式阻止它,在它集中之后。

【问题讨论】:

    标签: javascript typeahead.js twitter-typeahead


    【解决方案1】:

    看起来关闭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);
    });
    

    如果有人知道更好的方法来做到这一点,我会全力以赴!

    【讨论】:

    • 现在是 2018 年,这仍然是我发现可行的唯一方法。
    • @TimScarborough 实际上是 2019 年:D
    • 伙计们!你不知道我在 2020 年看到这个有多高兴!!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2020-05-01
    相关资源
    最近更新 更多