我正在尝试重用一些javascript / jquery
var my_conf = {
//I would like to re-use the 'source' definition
source: function (request, response) {
$.ajax({
url: site_url() + 'ajax_forms/auto_contact',
dataType: "json",
data: {
term: $("#creditor_name").val(),
search_city: $("#search_city").val()
},
success: function (data) {
var suggestions = [];
$.each(data,function(i, val){
suggestions.push(({label:data[i]['Description'], value: data[i]['Description'], real_value: data[i]['uniqContactID']}))
});
response(suggestions);
}
});
},
//The select definition isn't re-usable ... it changes in every use.
select: function(event, ui) {
$file_number = $("#hidden_file_number").val();
load_url = $("#hidden__url").val() + ui.item.real_value;
load_div = $("#hidden__div").val();
load_spinner = $("#hidden__spinner").val();
$(load_spinner).html(ajax_load);
$(load_div).empty().load(load_url);
},
minLength: 2
}
我必须在我的代码中的各个地方使用配置变量'my_conf'...但'source'部分始终是相同的...'select'部分总是不同。
我如何组织我的代码,以便我只写一次“来源”部分?
谢谢......简单的事情让我逃避。
答案 0 :(得分:0)
您可以将其放入命名函数并稍后重复使用。
function reuse_me(request, response) {
$.ajax({
url: site_url() + 'ajax_forms/auto_contact',
dataType: "json",
data: {
term: $("#creditor_name").val(),
search_city: $("#search_city").val()
},
success: function (data) {
var suggestions = [];
$.each(data,function(i, val){
suggestions.push(({label:data[i]['Description'], value: data[i]['Description'], real_value: data[i]['uniqContactID']}))
});
response(suggestions);
}
});
}
var my_conf = {
//I would like to re-use the 'source' definition
source: reuse_me,
//The select definition isn't re-usable ... it changes in every use.
select: function(event, ui) {
$file_number = $("#hidden_file_number").val();
load_url = $("#hidden__url").val() + ui.item.real_value;
load_div = $("#hidden__div").val();
load_spinner = $("#hidden__spinner").val();
$(load_spinner).html(ajax_load);
$(load_div).empty().load(load_url);
},
minLength: 2
}