我有几个jquery ui对象,它们都有类似的回调:
$(function() {
$("#my_list").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "api",
data: {
term: request.term,
},
success: response,
dataType: 'json',
minLength: 0,
});
},
minLength: 0,
select: function(event, ui) {
$('something').appendTo("#another_list");
}
}
});
});
如果我可以将“my_list”和“another_list”作为参数传递,那么代码会更清晰。 怎么办呢?
答案 0 :(得分:1)
将该代码包装在一个函数中?
function initAutocomplete(list1, list2){
$(list1).autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "api",
data: {
term: request.term,
},
success: response,
dataType: 'json',
minLength: 0,
});
},
minLength: 0,
select: function(event, ui) {
$('something').appendTo(list2);
}
}
});
}
$(function(){
initiAutocomplete('#my_list', '#another_list');
initiAutocomplete('#my_second_list', '#another_list_part_deux');
});