我收到错误“不要在循环中创建函数”。
我的代码是
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 :(得分: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);
}