我的页面上有很少的自动完成功能,但我有一个问题,一切正常,但问题是我不知道#ID我会怎么样,也许我可以创建一个函数并使用ID制作一些数组这样我就可以轻松维护代码,这是我现在拥有的那个?
$('#autocomplete-1').autocomplete({
source: autocompleteDataSource,
minLength: 3,
delay: 800,
appendTo: '#auto-complete-1',
select: autocompleteOnSelect,
open: function () {
setTimeout(function () { $("#ui-id-1").show(); }, 100);
},
response: function (event, ui) {
if (ui.content.length === 0) {
$(this).val("No results found");
} else {
$(this).empty();
}
}
});
$('#autocomplete-2').autocomplete({
source: autocompleteDataSource,
minLength: 3,
delay: 800,
appendTo: '#auto-complete-2',
select: autocompleteOnSelect,
open: function () {
setTimeout(function () { $("#ui-id-2").show(); }, 100);
},
response: function (event, ui) {
if (ui.content.length === 0) {
$(this).val("No results found");
} else {
$(this).empty();
}
}
});
$('#autocomplete-3').autocomplete({
source: autocompleteDataSource,
minLength: 3,
delay: 800,
appendTo: '#auto-complete-3',
select: autocompleteOnSelect,
open: function () {
setTimeout(function () { $("#ui-id-3").show(); }, 100);
},
response: function (event, ui) {
if (ui.content.length === 0) {
$(this).val("No results found");
} else {
$(this).empty();
}
}
});
需要在数组中创建所有ID然后循环进入函数吗?
答案 0 :(得分:2)
试试这个:
var arr = $('[id^=autocomplete-]');
$.each(arr, function(index, obj){
$('#autocomplete-' + (index+1)).autocomplete({
source: autocompleteDataSource,
minLength: 3,
delay: 800,
appendTo: '#autocomplete-' + (index+1),
select: autocompleteOnSelect,
open: function () {
setTimeout(function () { $('#ui-id-' + (index+1)).show(); }, 100);
},
response: function (event, ui) {
if (ui.content.length === 0) {
$(this).val("No results found");
} else {
$(this).empty();
}
}
});
});
答案 1 :(得分:0)
如果您向所有自动完成元素添加一个空的CSS类(如.autocomplete {}
),您可能会改变这样的函数:
$('.autocomplete').autocomplete({
source: autocompleteDataSource,
minLength: 3,
delay: 800,
appendTo: this.id,
select: autocompleteOnSelect,
open: function () {
setTimeout(function () { $(this). ??? show(); }, 100);
},
response: function (event, ui) {
if (ui.content.length === 0) {
$(this).val("No results found");
} else {
$(this).empty();
}
}
});
你基本上只有一个通用函数,不需要任何ID数组。
唯一的办法是以动态的方式识别ID为#ui-id-2
的后续孩子,这取决于你的布局(“???”在上面)
答案 2 :(得分:0)
你可以这样做,使用带选择器的启动:
$("[id^='autocomplete-']").autocomplete
rest of it
然后获取id为
var id = $(this).attr("id").split("autocomplete-")[1]
然后
var ui = $("#ui-id-_" + id)
会给你id。因此,您不需要保留数组以供参考,您可以从元素中获取id。
编辑:
$("[id^='autocomplete-']").autocomplete({
source: autocompleteDataSource,
minLength: 3,
delay: 800,
var id = $(this).attr("id").split("autocomplete-")[1] //gives you the id
appendTo: '#auto-complete-' + id,
select: autocompleteOnSelect,
open: function () {
setTimeout(function () { $("#ui-id-" + id).show(); }, 100);
},
response: function (event, ui) {
if (ui.content.length === 0) {
$(this).val("No results found");
} else {
$(this).empty();
}
}
});