Javascript 如何在jQueryUIAutoComplete中搜索多个属性?
我有一个对象数组,其结构类似于:Javascript 如何在jQueryUIAutoComplete中搜索多个属性?,javascript,jquery,angularjs,jquery-ui,jquery-ui-autocomplete,Javascript,Jquery,Angularjs,Jquery Ui,Jquery Ui Autocomplete,我有一个对象数组,其结构类似于: $scope.usersList = [{ "name": "John", "email": "john@xyz.com", "id": "abcd" },{ "name": "Jane", "email": "jane@xyz.com", "id": "efgh" }]; 在对服务器进行ajax调用之后,我得到了数组。我目前正在像这样的角度应用程序中使用jQueryUIAutoComplete $(input).autocomplet
$scope.usersList = [{
"name": "John",
"email": "john@xyz.com",
"id": "abcd"
},{
"name": "Jane",
"email": "jane@xyz.com",
"id": "efgh"
}];
在对服务器进行ajax调用之后,我得到了数组。我目前正在像这样的角度应用程序中使用jQueryUIAutoComplete
$(input).autocomplete({
source: $scope.usersList,
appendTo: container,
position: {
at: 'left bottom',
of: container
},
select: function(e, v) {
e.preventDefault();
//Do something
}
});
如果数组只是由名称组成,那么上面的代码可以工作,但是我想搜索“email”和“id”字段。e、 g.如果我在搜索框中键入“abcd”,我希望在结果列表中看到John的姓名。我无法确定如何继续此操作。请尝试按以下方式修改源代码:
$("#suggest").autocomplete({
delay: 100,
minLength:2,
**source: function (request, response) {
var temp = [];
usersList.filter(buildResponse);
function buildResponse(p){
for (var key in p) {
if (p.hasOwnProperty(key)) {
if(p[key].indexOf(request.term) > -1){
temp.push({
"label" : p[key],
"value" : p
});
}
}
}
}
console.log(temp);
response(temp);
}**,
select: function (event, ui) {
// Prevent value from being put in the input:
this.value = ui.item.label;
// Set the next input's value to the "value" of the item.
console.log(ui.item);
event.preventDefault();
}
});
//usersList=$scope.usersList(如问题中所述)
jshiddle:经过一段时间的磕磕绊绊之后,我成功地将搜索词设置为任意属性。这应该适用于您的情况(只需将
var usersList
替换为您的集合):
var usersList=[{
“姓名”:“约翰”,
“电子邮件”:john@xyz.com",
“id”:“abcd”
}, {
“姓名”:“简”,
“电子邮件”:jane@xyz.com",
“id”:“efgh”
}];
$(“#in”).autocomplete({
来源:功能(请求、响应){
函数hasMatch(s){
返回s.toLowerCase().indexOf(request.term.toLowerCase())!=-1;
}
变量i、l、obj、matches=[];
如果(request.term==“”){
答复([]);
返回;
}
对于(i=0,l=usersList.length;i
在这里工作:将
source
实现为一个函数,使用您需要的任何过滤逻辑。如果它解决了你的问题,你能接受答案吗?这只与id匹配。你能检查小提琴吗?啊,刚刚注意到它区分大小写。修复外壳,然后这是一个很好的清洁解决方案。
<input id="in" type="input" class="ui-autocomplete-input" />
var usersList = [{
"name": "John",
"email": "john@xyz.com",
"id": "abcd"
}, {
"name": "Jane",
"email": "jane@xyz.com",
"id": "efgh"
}];
$("#in").autocomplete({
source: function(request, response) {
function hasMatch(s) {
return s.toLowerCase().indexOf(request.term.toLowerCase()) !== -1;
}
var i, l, obj, matches = [];
if (request.term === "") {
response([]);
return;
}
for (i = 0, l = usersList.length; i < l; i++) {
obj = usersList[i];
if (hasMatch(obj.name) || hasMatch(obj.email) || hasMatch(obj.id)) {
if ($.inArray(obj, matches) < 1) { // remove duplicates
matches.push({
"label": obj.name
//add here other properties you might need
})
}
}
response(matches);
}
}
});