【问题标题】:bootstrap typeahead autocomplete returns multiple from same valuebootstrap typeahead 自动完成从相同的值返回多个
【发布时间】:2013-05-03 12:37:12
【问题描述】:

我有以下 jquery 函数,它将源作为来自服务器的 json。 但是当我在客户端运行这个脚本时,只要我输入,我就会从相同的值中获得多个,并且当我继续输入键时它会不断增加。

function autocomplete(html_field, request_url, hidden_field){
    var map = {};
    var objects = [];
    $(html_field).typeahead({
    minlength: 3,
    source: function (query, process) {
        return $.get(request_url, { query: query }, function (data) {
            $.each(data, function(i, obj){
                map[obj.translations__name] = obj;
                objects.push(obj.translations__name);
            });
            return process(objects);
            });
    },
    updater: function (item) {
        $(hidden_field).val(map[item].id);
        return item;
        }
    });
}

有什么想法吗?

【问题讨论】:

    标签: javascript jquery twitter-bootstrap bootstrap-typeahead


    【解决方案1】:

    我认为您必须在 .each() 函数之前清空数组对象,因为对于每个 jquery 调用,数据都会被推入数组中。

        source: function (query, process) {
            return $.get(request_url, { query: query }, function (data) {
                objects.splice(0, objects.length);
                $.each(data, function(i, obj){
                    map[obj.translations__name] = obj;
                    objects.push(obj.translations__name);
                });
                return process(objects);
                });
    

    你可以在这里看到空数组:How do I empty an array in JavaScript?

    【讨论】:

      猜你喜欢
      • 2018-06-23
      • 1970-01-01
      • 2012-06-13
      • 2022-06-24
      • 2015-01-16
      • 2018-05-14
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多