【问题标题】:Can I have typeahead/bloodhound always show what the user is typing?我可以让 typeahead/bloodhound 始终显示用户正在输入的内容吗?
【发布时间】:2020-12-28 11:55:11
【问题描述】:

我正在使用 typeahead/bloodhound 实现标签输入。用户可以添加新标签,而不受限于已经存在的标签。

我希望始终显示用户在建议列表中输入的内容,以便他们可以通过单击创建标签(目前他们可以通过输入逗号或输入回车来创建)。理想情况下,我可以通过在“建议”旁边显示新标签的小徽章来区分新标签和现有标签。

是否有可能做到这一点(如果可以,如何做到)?

我现在拥有的代码,它可以正常工作(除了不显示下拉菜单中输入的内容):

var tags = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  prefetch: {
    url: '/Tags/list.json',
    cache: false,
    filter: function(list) {   
      return $.map(list, function(tag) {
        return { name: tag }; });
    }
  }
});
tags.initialize();
}

$('.tags-wrapper input').tagsinput({
  typeaheadjs: {
    name: 'tags',
    displayKey: 'name',
    valueKey: 'name',
    source: tags.ttAdapter(),
  }
});

【问题讨论】:

    标签: twitter-bootstrap typeahead.js typeahead bloodhound


    【解决方案1】:

    我想通了!

    首先我补充说:

    templates: {
        empty: function(obj) {return '<div class="tt-suggestion tt-selectable tt-current-query">'+obj.query+' <span class="tt-new badge badge-info">New</span></div>';}
    }
    

    $('.tags-wrapper input').tagsinput({ ...

    然后我添加了一些新的 jquery 来检测用户何时点击新标签

    $(document).on("click", ".tt-current-query", function() {
        var input=$(this).closest('.twitter-typeahead').find('input.tt-input');
        input.trigger("keypress");
    });
    
    

    我不是 100% 确定为什么这仅适用于按键触发器,但确实如此!我很想知道为什么会这样 - 我花了一段时间尝试注入逗号或返回按键事件,最终偶然发现了这个解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多