for (a = 1; a <= 2; a++) {
$("#inp-" + a + " .nama").autocomplete({
source: function(request, response) {
$.ajax({
url: "states_remote.php",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
value: item.nama,
pangkat: item.pangkat,
jabatan: item.jabatan,
nip: item.nip
};
}));
}
});
},
minLength: 2,
select: function(event, ui) {
$("#inp-" + a + " .pangkat").val(ui.item.pangkat);
$("#inp-" + a + " .nip").val(ui.item.nip);
$("#inp-" + a + " .jabatan").val(ui.item.jabatan);
$(this).next('.nama').focus();
},
html: true,
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
}
我希望使用循环变量a
进入自动编译选择函数,但我无法访问此函数中的调用变量
select: function(event, ui) {
$("#inp-" + a + " .pangkat").val(ui.item.pangkat);
$("#inp-" + a + " .nip").val(ui.item.nip);
$("#inp-" + a + " .jabatan").val(ui.item.jabatan);
$(this).next('.nama').focus();
},
有人可以帮助我解决我的问题吗?我搜索其他主题也许这个名字是异步函数。
答案 0 :(得分:0)
尝试使用闭包: -
for (a = 1; a <= 2; a++) {
(function(a) {
$("#inp-" + a + " .nama").autocomplete({
source: function(request, response) {
$.ajax({
url: "states_remote.php",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
value: item.nama,
pangkat: item.pangkat,
jabatan: item.jabatan,
nip: item.nip
};
}));
}
});
},
minLength: 2,
select: function(event, ui) {
$("#inp-" + a + " .pangkat").val(ui.item.pangkat);
$("#inp-" + a + " .nip").val(ui.item.nip);
$("#inp-" + a + " .jabatan").val(ui.item.jabatan);
$(this).next('.nama').focus();
},
html: true,
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
})(a);
}
答案 1 :(得分:0)
还有另一种方式,我觉得这会更好:
$(".nama").autocomplete({ // <----all the ".nama" element will be initialized
source: function(request, response) {
$.ajax({
url: "states_remote.php",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
value: item.nama,
pangkat: item.pangkat,
jabatan: item.jabatan,
nip: item.nip
};
}));
}
});
},
minLength: 2,
select: function(event, ui) {
// event.target will be the ".nama" element and
// as per your code it seems that the elements are sibling
// elements of the ".nama", so use `.end()` to get back to
// $(event.target)
$(event.target).siblings(".pangkat").val(ui.item.pangkat).end()
.siblings(".nip").val(ui.item.nip).end()
.siblings(".jabatan").val(ui.item.jabatan);
$(event.target).focus();
},
html: true,
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});