javascript - Bootstrap typeahead 使用 json 对象而不是字符串

标签 javascript json twitter-bootstrap bootstrap-typeahead

我通过向 Bootstrap 传递一个简单的平面 json 字符串数组(如 ["php","php4","php5"])来进行预输入。在这种情况下,所有标准功能都可以满足我的要求。

但是我想以如下格式提供数据:

[
    {
        "name":"php",
        "count":123
    },
    {
        "name":"php4",
        "count":3532
    },
    {
        "name":"php5",
        "count":999
    }
]

然后我想格式化我的 typeahead 以同时使用 name 和 count。可能会产生一些看起来像 php5 (999) 的东西,当你选择 typeahead 时,它只会输出 php5。我认为如果我只是重写所有函数,这将很容易做到。

$('.input-classname').typeahead({
        source: function (query, process) {
            // Source here
        },
        updater: function (item) { // What gets sent to the input box
            return item.name;
        },
        highlighter: function(item) {
            return item.name + " (" + item.count + ")";
        },
        matcher: function (item) {
            // Do the matching
        },
        sorter: function (items) {
            // Do the sorting
        }
    });

这工作正常,但我想使用 highlightermatchersorterbase 版本> 做繁重的工作。我只是传入 item.name 而不是 item。但是我不知道如何获得这些功能的基本版本。有什么方法可以做到这一点吗?

最佳答案

当然,只需调用/应用 Typeahead 原型(prototype)上的方法,例如

var Typeahead = $.fn.typeahead.Constructor;

$(".input-classname").typeahead({
  // ...
  matcher: function (item) {
    // do something with item
    return Typeahead.prototype.matcher.call(this, item);
  },

  sorter: function (items) {
    // alternatively
    // do something with items
    return this.constructor.prototype.sorter.call(this, items);
  }
});

关于javascript - Bootstrap typeahead 使用 json 对象而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16366950/

相关文章:

twitter-bootstrap - Bootstrap Grid with Accordion 将底部单元格向右推

javascript - 如何在 NodeJS 中拆分和修改字符串?

javascript - 设置 iframe 样式的正确方法是什么?

javascript - 我可以设置弹出窗口获得焦点的时间长度吗?

javascript - 在 Ember.js 应用程序中编辑从 api 检索的数据

java - Gson如何反序列化空对象属性

javascript - jQuery如何读取json缓存?

javascript - Twitter-bootstrap 导航栏下拉菜单表现异常(不在移动设备上工作,不在桌面上显示)

javascript - 文本悬停在图像上

html - 如何在 Bootstrap 表中的带边框的两行之间添加空格