我正在尝试在data
参数中为自动填充发送不同的值,具体取决于之前设置的全局变量lookupType
。
但是,即使只有data
部分,所有其他代码也会重复。
如何减少冗余代码?
在一个案例中,data
部分是:
data: {
type: "full",
location: "local",
name: request.term
},
而另一个则是这样的:
data: {
append: "no",
doPreprocess: true,
name: request.term,
maxResults: 1000
},
完整代码如下:
$( "#lookup" ).autocomplete({
if($("#hiddenLookupType").val() == "order")
{
source: function( request, response ) {
$.ajax({
url: lookupUrl,
dataType: "jsonp",
data: {
type: "full",
location: "local",
name: request.term
},
success: function( data ) {
// do something
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
}
else if($("#hiddenLookupType").val() == "inventory")
{
source: function( request, response ) {
$.ajax({
url: lookupUrl,
dataType: "jsonp",
data: {
append: "no",
doPreprocess: true,
name: request.term,
maxResults: 1000
},
success: function( data ) {
// do something
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
}
});
答案 0 :(得分:0)
而不是:
data: {
type: "full",
location: "local",
name: request.term
},
有:
data: GetData(this),
function GetData(el)
{
..Logic Here
}
答案 1 :(得分:0)
//calling it:
var parameters = {
type: "full",
location: "local",
name: request.term
}
test(parameters);
//the method
function test(dataList){
$( "#lookup" ).autocomplete({
if($("#hiddenLookupType").val() == "order")
{
source: function( request, response ) {
$.ajax({
url: lookupUrl,
dataType: "jsonp",
data: dataList,
success: function( data ) {
// do something
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
}
else if($("#hiddenLookupType").val() == "inventory")
{
source: function( request, response ) {
$.ajax({
url: lookupUrl,
dataType: "jsonp",
data: {
append: "no",
doPreprocess: true,
name: request.term,
maxResults: 1000
},
success: function( data ) {
// do something
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
}
});
}