【问题标题】:From Jquery-ui autocomplete to typeahead.js从 Jquery-ui 自动完成到 typeahead.js
【发布时间】:2013-05-10 12:44:25
【问题描述】:

我正在将我的应用程序迁移到 twitter-bootstrap,并且我想用 typeahead.js 替换我的 jquery-ui 自动完成功能。

最好使用嵌入在 twitter-bootstrap 中的功能,但如果需要,我可以使用额外的 typeahead 插件。

我的问题是我无法重现当前行为,尤其是在没有结果的情况下。

你会怎么做这样的事情?

$("#search").autocomplete({
           source : myUrl,
            delay : 100,
            minLength : 2,
            select : function(event, ui) {
              // do whatever i want with the selected item
            },

            response : function(event, ui) {
                if (ui.content.length === 0) {
                    ui.content.push({
                        label : "No result",
                        value : customValue
                    });
                }
            }
        });

基本上,如果没有结果,我想在组件中显示一条自定义消息。

谢谢!

【问题讨论】:

标签: jquery-ui twitter-bootstrap bootstrap-typeahead typeahead.js


【解决方案1】:

向 Bootstrap typeahead 的迁移看起来像......

$('.typeahead').typeahead({
  minLength:2,
  updater: function (item) {
     /* do whatever you want with the selected item */

    },
  source: function (typeahead, query) {
     /* put your ajax call here..
     return $.get('/typeahead', { query: query }, function (data) {
        return typeahead.process(data);
     });
     */      
    }
});

编辑:

我更新了演示以包含 sorterhighlighter。我想这会给你你想要的结果..

  sorter: function(items) {
    if (items.length == 0) {
        var noResult = new Object();
        items.push(noResult);
    }
    return items;    
    },
  highlighter: function(item) {
    if (dataSource.indexOf(item) == -1) {
        return "<span>No Match Found.</span>";
    }
    else {
       return "<span>"+item+"</span>";
    }
  },

Bootstrap Typeahead Demo

我不认为 typeahead 相当于延迟,但是有一些 jquery 解决方法。

【讨论】:

  • 当我更多地考虑这一点时,我意识到这个答案是不够的。让 typeahead 显示“不匹配”是一个完全不同的问题,我不确定 Bootstrap typeahead.js 是否可以工作。可能有办法通过“匹配”功能。
  • 我用它做了更多工作并编辑了我的答案。再次查看演示:bootply.com/61459
  • 感谢您的编辑;)我会尽快听从您的建议。
【解决方案2】:

使用最新版本的 Typeahead.js (0.10),现在可以指定一个空模板以在未找到结果时显示。

   $('.typeahead').typeahead({
     hint: true,
     highlight: true,
     minLength: 2
    },{
      name: 'examples',
      source: examples.ttAdapter(),
      templates: {
        empty: [
          '<div class="empty-message">',
          'unable to find any results that match the current query',
          '</div>'
        ].join('\n')
      }
    });

【讨论】:

    猜你喜欢
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多