通过使用 typeahead bootstrap,我想在从菜单中选择或聚焦一个项目时触发,以便 设置与所选值相关的特定值。
请查看代码注释以准确理解我的意思。
element.typeahead({
minLength: 3,
source: function () {
// users is a Backbone.Collection
users = _.map(users, function(user) {
return user.get('first_name')+' '+user.get('last_name');
});
return users;
}
}).change(function (event) {
// this function which is called when the user set a value
// should be able to get the user.get('id') of the selected user
// any idea how to make it?
});
最佳答案
这可能对您有用。我使用 Typeahead 的扩展,允许您调用远程数据源。它带有一个 onselect()
回调函数,您可以在其中执行您想要的操作。
下面是一些示例代码:
initialization: function() {
this.user = new User();
// Or fetch the user so it has an id, etc.
},
initTypeahead: function() {
var self = this;
var element = this.$('#input');
element.typeahead({
source: userCollection.toJSON(),
property: 'name',
onselect: function(userObj) { // This is the line to pay attention to
var userModel = userCollection.get(userObj.id);
// Do something with the userModel
}
});
}
基本上在我的代码中,当我查询我的数据库时,我会返回一个 JSON,它将每个选择的值设置为我从 ajax 传回的任何数据。
通过 onselect(obj)
,我将 obj 传递到我的回调中,我恰好将它作为数据附加到输入元素。但是您可以轻松地添加您自己的自定义代码,利用您已有的用户数据 (user.id) 并执行您所做的任何操作以及您选择的值。这意味着,只要在适当的范围内,user.id 就应该在您的 onselect()
回调中可用。
关于javascript - typeahead bootstrap,当从菜单中选择或聚焦项目并获取值时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12111959/