我正在使用jQuery UI Autocomplete,在我的页面上我有三个输入来自动完成我试图处理这个:
var elem = $('.tags');
var groups = ["C","C++","Java","JavaScript","PHP","Python","Ruby"];
var users = ["John Doe","Jane Doe","Jim Doe"];
var ips = ["test1","test2","test3"];
elem.autocomplete({
source: elem.attr('data-remote-source').split(','),
});
但这对我不起作用,我在代码中做错了什么?
HTML代码如下:
<input type="search" name="" data-remote-source="groups" class="tags" placeholder="Search for groups" />
<input type="search" name="" data-remote-source="users" class="tags" placeholder="Search for users" />
<input type="search" name="" data-remote-source="ips" class="tags" placeholder="Search for ips" />
答案 0 :(得分:0)
elem.attr('data-remote-source')
正在返回字符串'groups'
它始终返回相同字符串elem
的原因是全局的(在自动完成初始值设定项之外)并匹配所有3个输入。 jQuery正在返回第一场比赛。
然后你试图用逗号分割该字符串,返回[ "groups" ]
以下是一个演示 - 所有3个自动填充功能都匹配“群组”而不是其他内容:http://jsfiddle.net/86y2W/
以下是修复:
var elem = $('.tags');
var data = {
"groups": ["C","C++","Java","JavaScript","PHP","Python","Ruby"],
"users": ["John Doe","Jane Doe","Jim Doe"],
"ips": ["test1","test2","test3"]
};
elem.each(function(i,e){
$(e).autocomplete({
source: data[$(e).attr('data-remote-source')]
});
});
这使用字符串(例如groups
)从data
变量中查找实际数组
同样的小提琴,用这段代码更新:http://jsfiddle.net/86y2W/1/