Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 扩展引导程序typeahead,以获取对象而不是字符串_Javascript_Jquery_Autocomplete_Twitter Bootstrap - Fatal编程技术网

Javascript 扩展引导程序typeahead,以获取对象而不是字符串

Javascript 扩展引导程序typeahead,以获取对象而不是字符串,javascript,jquery,autocomplete,twitter-bootstrap,Javascript,Jquery,Autocomplete,Twitter Bootstrap,为了获取对象而不是字符串,我扩展了引导程序typeahead。 这是可行的,但我想知道这是正确的做法 谢谢 参考资料: \扩展($.fn.typeahead.Constructor.prototype{ 渲染:函数(项){ var=这个; items=$(items).map(函数(i,item){ i=$(that.options.item) .attr('data-value',项[that.options.display]) .attr('data-id',item.id); i、 查找

为了获取对象而不是字符串,我扩展了引导程序typeahead。
这是可行的,但我想知道这是正确的做法

谢谢

参考资料:

\扩展($.fn.typeahead.Constructor.prototype{
渲染:函数(项){
var=这个;
items=$(items).map(函数(i,item){
i=$(that.options.item)
.attr('data-value',项[that.options.display])
.attr('data-id',item.id);
i、 查找('a').html(即.highlighter(项));
返回i[0];
});
items.first().addClass('active');
这是.$menu.html(项目);
归还这个;
},
选择:函数(){
var val=this.$menu.find('.active').attr('data-value'),
id=此.$menu.find('.active').attr('data-id');
这是$element
.val(此.updater(val,id))
.change();
返回这个。hide()
}
});
返回函数(元素、选项){
var getSource=函数(){
返回{
id:2,
全名:“名字姓氏”
};
};
元素.typeahead({
最小长度:3,
来源:getSource,
显示:“全名”,
分拣机:功能(项目){
var beginswith=[],
区分大小写=[],
不区分大小写=[],
项目,,
显示的项目;
while(item=items.shift()){
itemDisplayed=项[this.options.display];
如果(!itemDisplayed.toLowerCase().indexOf(this.query.toLowerCase())){
beginswith.push(项目);
}else if(~itemsdisplated.indexOf(this.query)){
区分大小写。推送(项目);
}否则{
不区分大小写。推送(项目);
}
}
返回beginswith.concat(区分大小写,不区分大小写);
},
荧光灯:功能(项目){
var query=this.query.replace(/[\-\[\]{}()*+?,\\\^$\\\s]/g,'\\$&');
返回项[this.options.display].replace(新的RegExp(“(“+query+”),“ig”),函数($1,match){
返回“”+匹配+”;
});
},
匹配器:功能(项目){
var值=项[this.options.display];
返回{
value:~value.toLowerCase().indexOf(this.query.toLowerCase()),
id:item.id
};
},
更新程序:函数(项,用户ID){
options.hiddenInputElement.val(userId);
退货项目;
}
});
};

我建议不要重写原型(这将影响到所有可以使用自动完成器的地方,而不仅仅是以下功能)。
此代码应适用于:

var getSource = function () {

    var users = new Backbone.Collection([
        {
            first_name: 'primo',
            last_name: 'ultimo',
            id: 1
        },
        {
            first_name: 'altro_primo',
            last_name: 'altro_ultimo',
            id: 2
        }
    ]).models;

    return _.map(users, function (user) {
        return {
            id: user.get('id'),
            full_name: user.get('first_name') + ' ' + user.get('last_name'),
            // these functions allows Bootstrap typehead to use this item in places where it was expecting a string
            toString: function () {
                return JSON.stringify(this);
            },
            toLowerCase: function () {
                return this.full_name.toLowerCase();
            },
            indexOf: function (string) {
                return String.prototype.indexOf.apply(this.full_name, arguments);
            },
            replace: function (string) {
                return String.prototype.replace.apply(this.full_name, arguments);
            }
        };
    });
};

$('.full_name').typeahead({
            minLength: 3,
            source: getSource(),
            display: 'full_name',
            updater: function (itemString) {
                var item = JSON.parse(itemString);
                $('.id').val(item.id);
                return item.full_name;
            }
});

演示:

除了@AntoJs answer之外,这里还有一个ajax版本(只是“源代码”部分):


顺便说一句:@AntoJs-非常感谢你的回答

@antonjs的答案对我不起作用,我得到了以下错误

TypeError:item.substr不是函数

因此,对于jQuery v2.1.3和bootstrap3-typeahead.js v3.1.0,以下内容适合我

var getSource=function(){
var users=new Backbone.Collection([
{
名字:“primo”,
姓氏:“ultimo”,
身份证号码:1
},
{
名字:“altro_primo”,
姓氏:“altro_ultimo”,
身份证号码:2
}
]).模型;
返回映射(用户,函数(用户){
返回{
id:user.get('id'),
全名:user.get('first_name')+''+user.get('last_name'),
//这些函数允许Bootstrap typehead在需要字符串的地方使用此项
toString:函数(){
返回JSON.stringify(this);
},
toLowerCase:函数(){
返回这个.full_name.toLowerCase();
},
indexOf:函数(字符串){
返回String.prototype.indexOf.apply(this.full_名称,参数);
},
替换:函数(字符串){
返回String.prototype.replace.apply(this.full_名称、参数);
},
substr:功能(开始,len){
返回此.full_name.substr(开始,len);
}
};
});
};
$('.full_name')。请提前键入({
最小长度:3,
来源:getSource(),
显示:“全名”,
更新程序:函数(itemString){
var item=JSON.parse(itemString);
$('.id').val(item.id);
return item.full_name;
}

});我不知道你是怎么走到这一步的。当我尝试运行代码时,
sorter()
方法中会抛出一个异常,用于尝试在对象上应用字符串方法。你在改变那个方法吗?或者向对象添加函数?是的,你是对的,因为我做了其他更改,但我还没有发布。。我等会儿再去。谢谢,这会很有帮助,因为
matcher()
sorter()
都会在传递给
render()方法之前更改
项。此外,API中还支持重写
sorter()
,因此不需要在bootstrap-typeahead.js源代码中对其进行编辑。(不是说你在做什么——只是指出来)看起来不错!我的唯一建议是:1)考虑在API上保持向后兼容性。现在,您正在引入新的选项,但没有定义默认值(例如,显示)。您应该扩展默认值,以便在省略新选项的情况下,始终存在一些回退功能。2) 您应该避免将数据模型(源)与插件的方法强耦合。具体来说,我
var getSource = function () {

    var users = new Backbone.Collection([
        {
            first_name: 'primo',
            last_name: 'ultimo',
            id: 1
        },
        {
            first_name: 'altro_primo',
            last_name: 'altro_ultimo',
            id: 2
        }
    ]).models;

    return _.map(users, function (user) {
        return {
            id: user.get('id'),
            full_name: user.get('first_name') + ' ' + user.get('last_name'),
            // these functions allows Bootstrap typehead to use this item in places where it was expecting a string
            toString: function () {
                return JSON.stringify(this);
            },
            toLowerCase: function () {
                return this.full_name.toLowerCase();
            },
            indexOf: function (string) {
                return String.prototype.indexOf.apply(this.full_name, arguments);
            },
            replace: function (string) {
                return String.prototype.replace.apply(this.full_name, arguments);
            }
        };
    });
};

$('.full_name').typeahead({
            minLength: 3,
            source: getSource(),
            display: 'full_name',
            updater: function (itemString) {
                var item = JSON.parse(itemString);
                $('.id').val(item.id);
                return item.full_name;
            }
});
$('.full_name').typeahead({
    /* ... */
    source: function(query,process){
    $.ajax({
        url: 'your_url_here',
        data: {term: query, additional_data: 'some_data'},
        success: function(data){
            process($.map(data, function(user){
                return {
                    id: user.id,
                    full_name: user.first_name + ' ' + user.last_name,
                    toString: function () {
                        return JSON.stringify(this);
                    },
                    toLowerCase: function () {
                        return this.full_name.toLowerCase();
                    },
                    indexOf: function (string) {
                        return String.prototype.indexOf.apply(this.full_name, arguments);
                    },
                    replace: function (string) {
                        return String.prototype.replace.apply(this.full_name, arguments);
                    }
                }
            }));
        }
    });
    },
/* ... */
});