2013-06-26 33 views
0

我是相當新的javacript,我試圖添加一個數值計數器作爲循環到以下功能,以節省我輸入8次!添加計數器到JavaScript函數循環

該函數需要被稱爲loadPopup1 - loadPopup8和#toPopup div需要toPopup1 - toPopup8。

這裏是我的代碼:

function loadPopup() { 
    if(popupStatus == 0) { // if value is 0, show popup 
     closeloading(); // fadeout loading 
     $("#toPopup").fadeIn(0500); // fadein popup div 
     $("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8 
     $("#backgroundPopup").fadeIn(0001); 
     popupStatus = 1; // and set value to 1 
    } 
} 

非常感謝您的幫助!

皮特

回答

2

交出參數的功能...

function loadPopup(index) { 
    ... 
    $("#toPopup" + index).fadeIn(0500); 
    ... 
} 

然後,如果你想採取行動的#1和#7,把它傳遞指數...

loadPopup(1); 
loadPopup(7); 
0

這個代碼將創建8個功能:

for (var i = 1; i <= 8; ++i) { 
    (function(i) { 
     window['loadPopup' + i] = function loadPopup() { 
      if(popupStatus == 0) { // if value is 0, show popup 
       closeloading(); // fadeout loading 
       $("#toPopup" + i).fadeIn(0500); // fadein popup div 
       $("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8 
       $("#backgroundPopup").fadeIn(0001); 
       popupStatus = 1; // and set value to 1 
      } 
     }; 
    })(i); 
} 
0
function loadPopup(i) { 
    if(popupStatus == 0) { // if value is 0, show popup 
     closeloading(); // fadeout loading 
     $("#toPopup" + i).fadeIn(0500); // fadein popup div 
     $("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8 
     $("#backgroundPopup").fadeIn(0001); 
     popupStatus = 1; // and set value to 1 
    } 
} 

var wrapper={}; 
for (var i =0; i < 8; i++){ 
    wrapper['loadPopup' + i] = new function(){loadPopup(i);}; 
} 

// so you can call 
wrapper.loadPopup3();