我正在使用TypeAhead为文本框提供自动完成结果。但是似乎Bloodhound或TypeAhead都只在搜索我提供的JSON数组中找到的第一个单词。

JSON如下所示:

[
    {
        "name": "ALICE",
        "value": "ALICE",
        "physical_address": "ERF 270 CNR. OF THOMPSON AND INTWANA STREET, ALICE",
        "province": "PROVINCE",
        "tokens": [
            "ALICE",
            "PROVINCE",
            "ERF",
            "270",
            "CNR.",
            "OF",
            "THOMPSON",
            "AND",
            "INTWANA",
            "STREET",
            "ALICE"
        ]
    },
    {
        "name": "BUTTERWORTH",
        "value": "BUTTERWORTH",
        "physical_address": "SHOP NO. 1 MASONIC SHOPPING COMP, COR HIGH & BELL STREET BUTTERWORTH 4960",
        "province": "PROVINCE",
        "tokens": [
            "BUTTERWORTH",
            "PROVINCE",
            "SHOP",
            "NO.",
            "1",
            "MASONIC",
            "SHOPPING",
            "COMP",
            "COR",
            "HIGH",
            "&",
            "BELL",
            "STREET",
            "BUTTERWORTH",
            "4960"
        ]
    }
]


我将TypeAhead初始化如下:

HTML:

<div class="films">
    <input type="text" class="form-control typeahead" placeholder="Search" name="films" autocomplete="off" id="search">
</div>


Javascript:

/* TypeAhead invoked */
var _prefetch_url = $root_path + '/media/mod_storelocator/stores_json.php';

// constructs the suggestion engine
var films = new Bloodhound({
    datumTokenizer: function (d) {
        return Bloodhound.tokenizers.whitespace(d.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 15,
    prefetch: _prefetch_url
});

// kicks off the loading/processing of `local` and `prefetch`
films.initialize();

$('.films .typeahead').typeahead(null, {
    displayKey : 'value',
    source: films.ttAdapter(),
    templates: {
        suggestion: Handlebars.compile([
            '<p class="repo-language">{{province}}</p>',
            '<p class="repo-name">{{name}}</p>',
            '<p class="repo-description">{{physical_address}}</p>'
        ].join(''))
    }
});


我真的很感谢任何帮助/指针。

最佳答案

您正在将d.value传递到datumTokenizer中,因此它仅使用数组中每个元素的value对象。

还要注意,Bloodhound会对数据本身进行标记化,因此您无需传递回JSON中的各个标记(即不需要tokens对象)。

因此,我将其更改为使用Bloodhound标记化数组中每个元素组合的valuephysical_address对象:

// constructs the suggestion engine
var films = new Bloodhound({
    datumTokenizer: function(d) {
                      return Bloodhound.tokenizers.whitespace(d.name);
                    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 15,
    prefetch: {
       url: _prefetch_url,
       filter: function(list) {
          return $.map(list,
                 function(element) {
                         return { name: element.value + " " + element.physical_address };
                 });
       }
    }
});


只能使用this fiddle在本地上下文中对此进行测试,但是预取应该以相同的方式工作。

10-07 21:14