2016-12-22 141 views
-1

我收到一條錯誤「不要在循環中創建函數」。如何優化JavaScript代碼

我的代碼是

var iframe = document.getElementById('contentFrame'); 
var innerDoc = iframe.contentDocument || iframe.contentWindow.document; 
var buttons =innerDoc.getElementsByClassName('RIC_Metrics'); 
var WTz_linkric_rp; 
for (var i = 0; i < buttons.length; i++) { 
    buttons[i].addEventListener('click', function() { 
    var DCSuri = "/edge/web/public/viewGroupBenefits/RIC"; 

    if(this.id === "Retirement Income Center") 
     WTz_linkric_rp = "TopNav_Retirement Income Centre"; 
    else(this.id === "Retirement Income Education") 
     WTz_linkric_rp = "TopNav_Retirement Income Education"; 


    var grpId = Bootstrapper.data.extract('groupNumberForPreSignIn', 'cookie'); 
    if (typeof window.dcsMultiTrack == "function") window.dcsMultiTrack("DCS.dcsuri", DCSuri, "WT.z_linkric_rp_test", WTz_linkric_rp,"WT.z_cookieric_rp_test", grpId); 
    }); 
}' 

我想呼籲各Click事件。任何幫助都被接受。我無法優化代碼。

+0

着對面的iframe訪問內容的文檔,而無需使用的postMessage API – mike510a

回答

0

嘗試把函數的循環之外,並在循環分配的功能:

var iframe = document.getElementById('contentFrame'); 
var innerDoc = iframe.contentDocument || iframe.contentWindow.document; 
var buttons =innerDoc.getElementsByClassName('RIC_Metrics'); 
var WTz_linkric_rp; 

function onClick() { 
    var DCSuri = "/edge/web/public/viewGroupBenefits/RIC"; 

    if(this.id === "Retirement Income Center") 
     WTz_linkric_rp = "TopNav_Retirement Income Centre"; 
    else(this.id === "Retirement Income Education") 
     WTz_linkric_rp = "TopNav_Retirement Income Education"; 


    var grpId = Bootstrapper.data.extract('groupNumberForPreSignIn', 'cookie'); 
    if (typeof window.dcsMultiTrack == "function") window.dcsMultiTrack("DCS.dcsuri", DCSuri, "WT.z_linkric_rp_test", WTz_linkric_rp,"WT.z_cookieric_rp_test", grpId); 
} 

for (var i = 0; i < buttons.length; i++) { 
    buttons[i].addEventListener('click', onClick, false); 
}