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 }32 }
闭包表现:js没有块级元素,数组记录的是最后一个的 。跟作用域等有关。
封装成内部函数,把i传人进内部函数,这样外部函数不会调用到内部函数的变量。
(function (i) { if ( childClassObjs[i].url) { $( childClassObjs[i].cName).click(function () { window.location.href = childClassObjs[i].url; }); } })(i);