webstrom
1.extact 抽取函数:选中代码,右键,refactor-extact
1 function matchPicLink() { 2 var $match = $('#match'); 3 var mWidth = Math.floor($match.width()); 4 var mWidthHalf = Math.floor(mWidth / 2); 5 $match.css({ 6 "width": mWidth, 7 // "height": Math.floor(mWidth * 757 / 692) //按原宽高比缩放,height=mWidth* height0/width0 8 "height": computeHeight(mWidth, 692, 757) 9 }); 10 var mHeight = $match.height(); 11 var mHeightHalf = Math.floor(mHeight / 2); 12 $(".poloShirt").css({ 13 "width": Math.floor(mHeight * 3 / 5), 14 "background": "rgba(9,200,200,0.5)", 15 "height": mHeightHalf 16 }); 17 $(".poloShirt").click(function () { 18 window.location.href = 'https://&0&商品id'; 19 }); 20 $(".vest").css({ 21 "width": mWidthHalf, 22 "background": "rgba(9,200,200,0.5)", 23 "height": mHeightHalf 24 }); 25 $(".vest").click(function () { 26 window.location.href = 'https://&0&商品id'; 27 }); 28 }
抽取函数,传入参数。哪些可以传参
因为子类有多个,所有将子类作为数组传入;并且子类含有很多属性和方法,如css以及click,所有数组中每个对象是json,即{key:value},调用的时候就是obj.key,所以将key作为参数传入。综合来看,就是
childClassObjs[i]={cName:cName,
ratioMoleculeW :ratioMoleculeW
ratioMoleculeH :ratioMoleculeH
url:url
}
1 function picLinkInit(parentClassName, imgW, imgH, childClassObjs) { 2 var $match = $(parentClassName); 3 var mWidth = Math.floor($match.width()); 4 5 var mHeight = computeHeight(mWidth, imgW, imgH); 6 $match.css({ 7 "width": mWidth, 8 "height": mHeight 9 }); 10 for (var i = 0; i < childClassObjs.length; i++) { 11 var childClassObj = childClassObjs[i]; 12 13 $(childClassObj.cName).css({ 14 "width": Math.floor(mWidth * childClassObj.ratioMoleculeW / childClassObj.ratioDenominatorW), 15 // "background": "rgba(9,200,200,0.5)", 16 "height": Math.floor(mHeight * childClassObj.ratioMoleculeH / childClassObj.ratioDenominatorH) 17 }); 18 /* if (childClassObj.url) { 19 $(childClassObj.cName).click(function () { 20 window.location.href =childClassObj.url; 21 }); 22 }*/ 23 (function (i) { 24 if ( childClassObjs[i].url) { 25 $( childClassObjs[i].cName).click(function () { 26 window.location.href = childClassObjs[i].url; 27 }); 28 } 29 })(i); 30 31 }
调用的时候是:

1 function matchPicLink4() { 2 picLinkInit("#match4", 692, 677, [ 3 { 4 "cName": ".aca4coat1", 5 "ratioMoleculeW": 16, 6 "ratioDenominatorW": 24, 7 "ratioMoleculeH": 7, 8 "ratioDenominatorH": 24, 9 "url": "https://&0&0&4675" 10 }, { 11 "cName": ".aca4coat2", 12 "ratioMoleculeW": 10, 13 "ratioDenominatorW": 24, 14 "ratioMoleculeH": 7, 15 "ratioDenominatorH": 24, 16 "url": "https://&0&0&4675" 17 } 18 ]); 19 }