使用typeahead和JSON只能使用第一个字母

时间:2016-04-06 17:22:01

标签: jquery typeahead.js materialize bloodhound

搜索Typeahead和Bloodhound文档我找不到有用的东西,因为我只是在输入第一个字母时才得到建议,但我继续输入单词和它找不到匹配。我找到了一种阅读JSON并在this question上过滤它的方法,但没有别的。似乎单词识别并不像预期的那样工作。请有这段代码经验的人可以告诉我我失踪的事情。

JAVASCRIPT

var globalCats = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,
    prefetch: {
        url: 'js/data.json',
        filter: function (list) {
            return $.map(list, function (item) {
            return {
                nombre: item.nombre,
                id: item.id,
                padre: item.padre
            };
        });
     }
    }
});

globalCats.initialize();
    $('.typeahead').typeahead({
         highlight: true
    },
    {
         name: 'recomendaciones',
         displayKey: 'nombre',
         source: globalCats.ttAdapter(),
         templates: {
             empty: [
                 '<div class="card red white-text"><strong>No hay sugerencias para su búsqueda</strong></div>'
             ].join('\n'),
             suggestion: Handlebars.compile('<div class="card"><a href="busqueda.php?catid={{id}}"><strong>{{nombre}}</strong> - Departamento {{padre}}</a></div>')
             }
    });

HTML

<form class="col s12 z-depth-1">
     <div class="row">
          <div class="col s12">
               <p>Ingrese sus términos de búsqueda o de click en Solicitar Servicio para publicar su requerimiento en sus redes sociales.</p>
          </div>
          <div class="input-field col s12 m9">
               <input id="buscador" type="text" placeholder="VEAMOS" class="typeahead">
          </div>
    </div>
</form>

JSON

[
    {
        "nombre": "Operadores de Taladradoras",
        "id": 111454,
        "padre": "Construcción"
    },
    {
        "nombre": "Operadores de Maquinaria",
        "id": 454654,
        "padre": "Construcción"
    },
    {
        "nombre": "Estilistas",
        "id": 454678,
        "padre": "Belleza"
    }
]

1 个答案:

答案 0 :(得分:0)

datumTokenizer错误。

我不太了解这一部分,但我发现在我尝试过的所有变体中似乎都有效。标记生成器需要引用您要返回的对象。因此,将tokenizer从默认值更改为:

Bloodhound.tokenizers.obj.whitespace('nombre'),

另外,我建议更改为remote而不是prefetch,除非您确定返回的数据量非常小。

Here is a link一个有效的例子。

相关问题