我在表单上多次调用jquery自动完成功能。我怎样才能将以下javascript重构为函数?
$(document).ready(function () {
$("#Style").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Beer/AutoStyle",
type: "GET",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Style,
value: item.Style
}
}));
}
});
}
});
});
我无法弄清楚如何对此
进行参数化 return {
label: item.Style,
value: item.Style
}
所以我的功能就是这样的
function AutoCompleteTemplate(tagID){
$(document).ready(function () {
$("#"+tagID).autocomplete({
source: function (request, response) {
$.ajax({
url: "/Auto"+tagID,
type: "GET",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.tagID,
value: item.tagID
}
}));
}
});
}
});
});
}
答案 0 :(得分:0)
您需要使用bracket notation作为member operator,因为tagID
是包含实际属性键的变量
function AutoCompleteTemplate(tagID) {
$("#" + tagID).autocomplete({
source: function (request, response) {
$.ajax({
url: "/Auto" + tagID,
type: "GET",
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item[tagID],
value: item[tagID]
}
}));
}
});
}
});
}