创建一个js文件,名为testClosure.js:
(function () {
function a()
{
alert('i am a');
}
outFunc = function () {
a();
}
})();
只需要暴露一个outFunc这个函数供外界调用。这个函数呢没有用var定义,就变成一个全局变量,外界就可以调用的到,利用这一点,让这个函数变成匿名函数和外界沟通的桥梁。
再利用js面向对象的方法,就可以封装出非常好用的组件。
(function()
{
var arrAuthItem = new Array();
var isInited = false;
var syncTableObj=findObj("sync-table-id",document);
var newTR=null;
var checkBox=null;
var authTable = null;
var selfPicUrl=null;
var selfItem=null;
var isAuthItemEnabled=false;
var isSelfItemEnabled=false;
function getAuthShopCurrent()
{
return $("#"+globalSyncVars.serverComClientId.AuthShopListId).val();
}
function getSyncFieldCurrent()
{
return $("#"+globalSyncVars.serverComClientId.SyncFieldListId).val();
}
function setTitle()
{
$("#sync-table-title-id").html("从“"+getAuthShopCurrent()+"”同步");
}
function getNumIidFrom(numIidTo)
{
var curRowData = jQuery("#listItemDefine").jqGrid('getRowData', numIidTo);
return curRowData.NumIidFrom;
}
function insertRows()
{
deleteAll();
for(var i=0;i';
if(getEnabledStatus(isBinded,!isSharedTo,isSelfItemEnabled))
isEnabled = true;
strTr+=''+getRadioCode(isBinded,!isSharedTo,isSelfItemEnabled,i,arr.length)+' '+picUrl+' '+getAuthItemCode(arr[p],isSharedFrom,isSharedTo,i)+' '+getEnabledCode(isBinded,!isSharedTo,isSelfItemEnabled,arr[p],numIid)+' ';
}
authTable.innerHTML = strHead+strTr+'';
return isEnabled;
}
// 返回auth宝贝详情html代码
function getAuthItemCode(obj,isSharedFrom,isSharedTo,i)
{
var labelStr = "";
if(isSharedFrom) labelStr = '【源】';
if(isSharedTo) labelStr = '【受】';
return ''+labelStr+'ID:' + obj["NumIid"] + ''
+ '商家编码:' + obj["OuterId"] + ''
+ '价格:' + obj["Price"] + ''
+ '
' + obj["Title"] + '';
}
// 返回self宝贝详情html代码
function getSelfItemCode(obj)
{
var labelStr = "";
if(stringToBoolean(obj["IsToItemHasShareFrom"])) labelStr = '【源】';
if(stringToBoolean(obj["IsToItemHasShareTo"])) labelStr = '【受】';
return ''+labelStr+'ID:' + obj["NumIidTo"] + ''
+ '商家编码:' + obj["OuterIdTo"] + ''
+ '价格:' + obj["PriceTo"] + ''
+ '
' + obj["TitleTo"] + '';
}
// 返回绑定关系图标的html代码
function getEnabledCode(isBinded,isAuthEnabled,isSelfEnabled,obj,numIid)
{
if(isBinded)
{
// 如果是绑定状态,还要看当前item是否为绑定的item
// 在这种情况下,判断是否可绑定,不需要用到selfItem
if(obj["NumIid"]==numIid)
return '';
else
{
if(stringToBoolean(obj["IsFromItemHasShareTo"]))
return '';
else
return '';
}
}else
{
if(isAuthEnabled&&isSelfEnabled)
return '';
else
return '';
}
}
// 是否可以绑定
function getEnabledStatus(isBinded,isAuthEnabled,isSelfEnabled)
{
if(isBinded) return false;
if(isAuthEnabled&&isSelfEnabled)
{
return true;
}
else
{
return false;
}
}
// 返回radio的html代码
/**
* isBinded 是否已经绑定
* isAuthEnabled auth是否可同步
* isSelfEnabled self是否可同步
* 当前rows的index
* 当前auth-list的长度(如果是一对一,当然不需要radio)
*/
function getRadioCode(isBinded,isAuthEnabled,isSelfEnabled,i,length)
{
if(isBinded) return "";
if(length==1) return "";
if(isAuthEnabled==false||isSelfEnabled==false) return "";
return '';
}
function setterSelfItem(i)
{
var isEnabled=true;
var picUrl='';
selfPicUrl.innerHTML = picUrl;
selfItem.innerHTML = getSelfItemCode(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]);
if(stringToBoolean(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["IsToItemHasShareFrom"])) isEnabled = false;
if(stringToBoolean(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["IsToItemHasShareTo"])) isEnabled = false;
return isEnabled;
}
function getPriceColor(price,i)
{
if(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["PriceTo"]==undefined) return "black";
if(price==undefined) return "black";
return (price==arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["PriceTo"])?"black":"red";
}
function setterEnableStatus(isEnabled,i)
{
if(isEnabled)
checkBox.innerHTML='';
else
checkBox.innerHTML='';
}
function stringToBoolean(str)
{
if (str==undefined) return false;
switch(str.toLowerCase())
{
case "true": case "yes": case "1": return true;
case "false": case "no": case "0": case null: return false;
default: return Boolean(str);
}
}
function deleteAll()
{
for(var i=syncTableObj.rows.length-1;i>2;i--)
{
syncTableObj.deleteRow(i);
}
}
function selectAll(isSelect)
{
if(isSelect)
{
$(".enableCheckbox").prop("checked",true);
}else
{
$(".enableCheckbox").prop("checked",false);
}
}
function findObj(theObj, theDoc)
{
var p, i, foundObj;
if(!theDoc) theDoc = document;
if((p = theObj.indexOf("?")) > 0 && parent.frames.length)
{
theDoc = parent.frames[theObj.substring(p+1)].document;
theObj = theObj.substring(0,p);
}
if(!(foundObj = theDoc[theObj]) && theDoc.all)
foundObj = theDoc.all[theObj];
for (i=0; !foundObj && i < theDoc.forms.length; i++)
foundObj = theDoc.forms[i][theObj];
for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)
foundObj = findObj(theObj,theDoc.layers[i].document);
if(!foundObj && document.getElementById)
foundObj = document.getElementById(theObj);
return foundObj;
}
function refrash()
{
deleteAll();
if(!isInited)
return;
setTitle();
//现在js还没有数据的,去取值
if(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""]==null)
{
var urledit="./x.aspx?method=GetAuthItem&rmd="+Math.random();
$.post(urledit,$("#"+globalSyncVars.serverComClientId.form1).serialize())
.done(function(myJsonResult) {
var data = $.evalJSON(myJsonResult);
ajaxResponseResult(data);
if (data.IsSuccess) {
arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""]=data.rows;
insertRows();
$("#sync-table-id").css("display","inline-table");
}
})
.fail(function(data) {
ajaxResponseResult(data);
})
.always(function(myJsonResult) {
});
}else
{
insertRows();
}
}
function checkIsEnabledBind(i)
{
if(stringToBoolean(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["IsFromItemHasShareTo"])) return false;
if(stringToBoolean(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["IsToItemHasShareFrom"])) return false;
if(stringToBoolean(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["IsToItemHasShareTo"])) return false;
return true;
}
function setSyncValueToCom()
{
var numIidsSelf="";
var numIidsAuth="";
var isBind="";
var isRadioUnChecked = false;
$(".enableCheckbox:checked").each(function()
{
if(checkIsEnabledBind($(this).attr("index")))
{
var checkBoxIndex = $(this).attr("index");
var radioIndex = 0;
isRadioUnChecked = false;
// 通过[0]判断radio是否存在
if($('input:radio[name=radio'+checkBoxIndex+']')[0])
{
var isCheckedLabel = false;
// 检查每个radio选项是否被选择
$('input:radio[name=radio'+checkBoxIndex+']').each(function()
{
if($('input:radio[name=radio'+checkBoxIndex+']')[radioIndex].checked)
{
isCheckedLabel = true;
// 这里是跳出each循环(里层)
return false;
}
radioIndex++;
});
if(!isCheckedLabel)
isRadioUnChecked = true;
// 如果存在checkbox有选择,但是radio没选择,应该提醒
// 然后就退出了,没有后续的提交
if(isRadioUnChecked)
{
checkBoxIndex++;
alert("第"+checkBoxIndex+"个宝贝有多个对应的授权宝贝,应该仔细查看并选择合适的宝贝同步!");
// 这里跳出循环(外层)
return false;
}
}
var arrAuth = arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][checkBoxIndex]["ListItemFrom"]
if(numIidsSelf=="")
{
numIidsSelf+=arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][checkBoxIndex]["NumIidTo"];
}else
{
numIidsSelf+=","+arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][checkBoxIndex]["NumIidTo"];
}
if(numIidsAuth=="")
{
numIidsAuth+=arrAuth[radioIndex]["NumIid"];
}else
{
numIidsAuth+=","+arrAuth[radioIndex]["NumIid"];
}
}
});
isBind=$("#isBind:checked").val()=="on"?"true":"false";
$("#"+globalSyncVars.serverComClientId.HfNumIidsSelf).val(numIidsSelf);
$("#"+globalSyncVars.serverComClientId.HfNumIidsAuth).val(numIidsAuth);
$("#"+globalSyncVars.serverComClientId.HfIsBind).val(isBind);
if(isRadioUnChecked) return -1;
if(numIidsSelf=="") return 0;
else return 1;
}
initTable=function()
{
refrash();
isInited=true;
}
onSelectAllCheckbox=function()
{
if($("#selectAllCheckbox:checked").val()=="on")
{
selectAll(true);
}else
{
selectAll(false);
}
}
onPreview=function()
{
refrash();
}
onAldsItemSync=function(sender,jqgridObjRefresh)
{
var callbackCode = setSyncValueToCom();
if(callbackCode == 0)
{
alert("没有可以同步设置的宝贝!");
return;
}else if(callbackCode == -1)
{
// 当存在没有选择的radio时
return;
}
var urledit="./x.aspx?method=SaveSyncItem&rmd="+Math.random();
$.post(urledit,$("#"+globalSyncVars.serverComClientId.form1).serialize())
.done(function(myJsonResult) {
var data = $.evalJSON(myJsonResult);
ajaxResponseResult(data);
if (data.IsSuccess)
{
showPrompt(data.PromptMsg);
if(sender)
{
$(sender).dialog("close");
$(sender).dialog("destroy");
}
if(jqgridObjRefresh)
{
$(jqgridObjRefresh).trigger("reloadGrid");
}
}
})
.fail(function(data) {
ajaxResponseResult(data);
})
.always(function(myJsonResult) {
});
}
})();
(function(){
//____________________________批量修改的基类_________________________________
function BatchModify(){}
//选择了什么id
BatchModify.prototype.numIids=null;
BatchModify.prototype.addis=null;
BatchModify.prototype.oneIid=null;
BatchModify.prototype.skuIds=null;
BatchModify.prototype.selectedItemData=null;
BatchModify.prototype.maxHeightVal=$(window).height()*0.9;
// 完全克隆一个数组
BatchModify.prototype.cloneArr=function(arr)
{
var arrNew = [];
for(var i=0;i=0?this.title.substring(4):this.title],
colModel:[
{name:'PicUrl', index: 'PicUrl', width: 60, align: "center", sortable: false, formatter: imgFormatter, unformat:imgUnFormat},
{name:'Title',index:'OuterId', width:430, sortable: true, formatter: itemDescFormatter, unformat:itemDescUnFormat},
{name:'NumIid',index:'NumIid', width:100, hidden:true, key:true},
{name:'Price',index:'Price', width:100, hidden:true},
{name: 'OuterId', index: 'OuterId', width: 100, hidden: true },
{name: this.fieldName, index: this.fieldName, width: 440, sortable: true, hidden: false, formatter:this.formatter}
]
});
};
//把表格填充进数据
BatchMsgModify.prototype.initTable=function()
{
var gridArrayData=[];
for(var i=0;i"+rowdata[currentInstance.fieldName]+"";
};
//重写post函数
BatchMsgModify.prototype.postData=function(urledit,sender)
{
$.post( urledit, $("#"+globalVars.serverComClientId.formAldsItemDefine1).serialize())
.done(function(myJsonResult)
{
var data = $.evalJSON(myJsonResult);
ajaxResponseResult(data);
if (data.IsSuccess) {
if (!data.rows)
showPrompt(currentInstance.title+"成功"+currentInstance.numIids.length+"个!");
$("#listItemDefine").trigger('reloadGrid');
setTimeout(function () { $(sender).dialog("close"); }, 0);
setTimeout(function () { $(sender).dialog("destroy"); }, 1000);
}
if(data.ErrMsg && $.trim(data.ErrMsg) != "")
alert(currentInstance.title+"出错:\n\n" + data.ErrMsg);
})
.fail(function(data) {
ajaxResponseResult(data);
})
.always(function(myJsonResult) {
});
};
//确认按钮的回调函数
BatchMsgModify.prototype.confirmCallback=function(sender)
{
this.setAddis();
this.setNumIidsToCom();
this.setAddisToCom();
this.postData(this.editUrl+"&rdm=" + Math.random(),sender);
};
//实例
var batchAddi=null;
var batchMsgTradeSuccess=null;
var batchMsgRatedGood=null;
var currentInstance=null;//指向当前对象,当this指向失效的时候可以使用这个
openBatchMsgDialogType={batchAddi:0,batchMsgTradeSuccess:1,batchMsgRatedGood:2};
openBatchMsgDialog=function(typeCode)
{
if(typeCode==openBatchMsgDialogType.batchAddi)
{
if (batchAddi==null)
batchAddi=new BatchMsgModify("批量修改附言","tableEditContent","tablePaper","Additional","x.aspx?method=UpdateMsgAdditional","
");
currentInstance=batchAddi;
batchAddi.cancelBindedItem();
batchAddi.setNumIids();
if(!batchAddi.checkIsSelected())
return;
batchAddi.popUpDialog();
batchAddi.createTable();
batchAddi.initTable();
}else if (typeCode==openBatchMsgDialogType.batchMsgTradeSuccess)
{
if (batchMsgTradeSuccess==null)
batchMsgTradeSuccess=new BatchMsgModify("批量修改确认收货后发消息","tableEditMsgTradeSuccessContent","tableMsgTradeSuccessPaper","MsgTradeSuccess","x.aspx?method=UpdateMsgTradeSuccess","
");
currentInstance=batchMsgTradeSuccess;
batchMsgTradeSuccess.cancelBindedItem();
batchMsgTradeSuccess.setNumIids();
if(!batchMsgTradeSuccess.checkIsSelected())
return;
batchMsgTradeSuccess.popUpDialog();
batchMsgTradeSuccess.createTable();
batchMsgTradeSuccess.initTable();
}else if (typeCode==openBatchMsgDialogType.batchMsgRatedGood)
{
if (batchMsgRatedGood==null)
batchMsgRatedGood=new BatchMsgModify("批量修改好评后发消息","tableEditMsgRatedGoodContent","tableMsgRatedGoodPaper","MsgRatedGood","x.aspx?method=UpdateMsgRatedGood","
");
currentInstance=batchMsgRatedGood;
batchMsgRatedGood.cancelBindedItem();
batchMsgRatedGood.setNumIids();
if(!batchMsgRatedGood.checkIsSelected())
return;
batchMsgRatedGood.popUpDialog();
batchMsgRatedGood.createTable();
batchMsgRatedGood.initTable();
}
}
//_______________________________批量修改宝贝类(弹出单独页面,只要弹窗即可)_________________________________
function BatchItemModify(){}
myInherits(BatchItemModify,BatchModify);
//重写
BatchItemModify.prototype.popUpDialog=function()
{
var urledit = "./x.aspx?NumIids="+this.numIids+"&rdm="+Math.random();
$.get(urledit, {}, function (data, textStatus, object) {
var str = "" + object.responseText + "";
$(str).dialog({
dialogClass: "untitle",
closeText: '关闭',
width: 800,
height: 400,
maxHeight: $(window).height() * 0.9,
modal: true,
show: { effect: "fade", duration: 300 },
hide: { effect: "fade", duration: 300 },
buttons: {
确定: function() {
submitAldsItemEditBatch(this, $("#listItemDefine")); //在x.aspx定义
currentInstance.batchGenerateDesc();
},
关闭: function() {
$( this ).dialog( "close" );
}
}
});
});
}
//实例
var batchItem=null;
openBatchItemDialog=function()
{
if (batchItem==null)
batchItem=new BatchItemModify();
currentInstance=batchItem;
batchItem.cancelBindedItem();
batchItem.setNumIids();
if(!batchItem.checkIsSelected())
return;
batchItem.popUpDialog();
}
//_______________________________批量生成宝贝描述__________________________________________
function BatchDescModify(){}
myInherits(BatchDescModify,BatchModify);
BatchDescModify.prototype.generating=function()
{
if (!confirm("提醒。\n\n是否继续?"))
return;
this.batchGenerateDesc(true);
};
//实例
var batchDesc=null;
onBatchDesc=function()
{
if(batchDesc==null)
batchDesc=new BatchDescModify();
currentInstance=batchDesc;
batchDesc.setNumIids();
if(!batchDesc.checkIsSelected())
return;
batchDesc.generating();
}
//_____________________________________修改模板______________________________________________
onDescMouldDialog=function()
{
var urledit = "./x.aspx?rdm="+Math.random();
$.get(urledit,{},function(data,textStatus,object){
var str=""+object.responseText+"";
$(str).dialog({
title:'修改描述模板',
closeText:'关闭',
width:850,
maxHeight:$(window).height() * 0.98,
modal:true,
show:{effect:"fade",duration:300},
hide:{effect:"fade",duration:300},
buttons:{
确定:function()
{
onTempParaChangeHandler(this);
},
关闭:function()
{
$(this).dialog("close");
}
}
});
});
}
//___________________________________批量修改sku_______________________________________
function BatchSkuModify(){}
myInherits(BatchSkuModify,BatchModify);
BatchSkuModify.prototype.popUpDialog=function()
{
var urledit = "./x.aspx?NumIids="+this.oneIid+"&SkuIds="+this.skuIds+"&IsSkuEditBatch=true&rdm="+Math.random();
$.get(urledit, {}, function (data, textStatus, object) {
var str = "" + object.responseText + "";
$(str).dialog({
dialogClass: "untitle",
closeText: '关闭',
width: 800,
height: 400,
maxHeight: $(window).height() * 0.9,
modal: true,
show: { effect: "fade", duration: 300 },
hide: { effect: "fade", duration: 300 },
buttons: {
确定: function() {
submitAldsItemEditBatch(this, $("#listSkuDefine")); //在x.aspx定义
},
关闭: function() {
$( this ).dialog( "close" );
}
}
});
});
};
BatchSkuModify.prototype.checkIsSelected=function()
{
if (this.skuIds == "") {
alert("请选中要批量修改的SKU!");
return false;
}
return true;
};
//实例
var batchSku=null;
openBatchSkuDialog=function()
{
if(batchSku==null)
batchSku=new BatchSkuModify();
currentInstance=batchSku;
batchSku.setOneIid();
batchSku.setSkuIds();
batchSku.removeDialog();
if(!batchSku.checkIsSelected())
return;
batchSku.popUpDialog();
}
//_______________________________批量修改SKU附言__________________________________________________
function BatchSkuMsgModify(title,tableId,paperId,fieldName,editUrl,containerDivStr)
{
BatchModify.call();
this.title=title;
this.tableId=tableId;
this.paperId=paperId;
this.fieldName=fieldName;
this.editUrl=editUrl;
this.containerDivStr=containerDivStr;
}
myInherits(BatchSkuMsgModify,BatchModify);
BatchSkuMsgModify.prototype.popUpDialog=function()
{
$(this.containerDivStr).dialog({
title: this.title,
closeText: '关闭',
width: 980,
maxHeight: this.maxHeightVal,
// height: this.maxHeightVal>750 ? 750 : this.maxHeightVal,
modal: true,
show: { effect: "fade", duration: 300 },
hide: { effect: "fade", duration: 300 },
buttons: {
确定: function() {
currentInstance.confirmCallback(this);
},
关闭: function() {
$(this).dialog("close");
}
}
});
};
//重写-创建表格
BatchSkuMsgModify.prototype.createTable=function()
{
$("#"+this.tableId).jqGrid({
viewrecords: true, // show the current page, data rang and total records on the toolbar
datatype: 'local',
rowNum:100,
rowList:[100],
height: "auto",
pager: "#"+this.paperId,
colNames:['SkuId','属性名',this.title.indexOf("批量修改")>=0?this.title.substring(4):this.title],
colModel:[
{name:'SkuId',index:'SkuId', width:400, hidden:true, key:true},
{name:'PropertiesName',index:'PropertiesName', width:400,sortable:false, editable: false, hiden:false},
{name: this.fieldName, index: this.fieldName, width: 440, sortable: true, hidden: false, formatter:this.formatter}
]
});
};
//把表格填充进数据
BatchSkuMsgModify.prototype.initTable=function()
{
var gridArrayData=[];
for(var i=0;i"+rowdata[currentInstance.fieldName]+"";
};
//重写post函数
BatchSkuMsgModify.prototype.postData=function(urledit,sender)
{
$.post( urledit, $("#"+itemEditVars.itemEditClientId.formAldsItemEdit1).serialize())
.done(function(myJsonResult)
{
var data = $.evalJSON(myJsonResult);
ajaxResponseResult(data);
if (data.IsSuccess) {
if (!data.rows)
showPrompt(currentInstance.title+"成功"+currentInstance.skuIds.length+"个!");
$("#listSkuDefine").trigger('reloadGrid');
setTimeout(function () { $(sender).dialog("close"); }, 0);
setTimeout(function () { $(sender).dialog("destroy"); }, 1000);
}
if(data.ErrMsg && $.trim(data.ErrMsg) != "")
alert(currentInstance.title+"出错:\n\n" + data.ErrMsg);
})
.fail(function(data) {
ajaxResponseResult(data);
})
.always(function(myJsonResult) {
});
};
//重写-拼装json
BatchSkuMsgModify.prototype.setAddis=function()
{
var _addis="{rows:{";
for(var i=0;i
参见本人另一篇文章:
javascript面向对象编程总结:http://blog.csdn.net/wzj0808/article/details/51591152