【问题标题】:Bootstrap typeahead with json object instead of string使用 json 对象而不是字符串引导预先输入
【发布时间】:2013-04-28 07:57:33
【问题描述】:

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

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

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

因此,我想格式化我的预输入以同时使用名称和计数。也许会产生一些看起来像 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
        }
    });

这很好用,但我想使用highlighter、matcher 和sorter 的base 版本来完成繁重的工作。我只是传入item.name 而不是item。但是我不知道如何获得这些功能的基本版本。有没有办法做到这一点?

【问题讨论】:

    标签: javascript json twitter-bootstrap bootstrap-typeahead


    【解决方案1】:

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

    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);
      }
    });
    

    【讨论】:

    • 分拣机不工作。它接受字符串列表,而不是对象列表 - 如果将对象名称映射到字符串,则荧光笔 item.name 将不起作用。
    • 答案的重点是如何在能够调用原始方法的同时修改原型方法。更新了代码,使这两个示例顺利通过。
    猜你喜欢
    • 2012-11-26
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多