可能重复:
Event handlers inside a Javascript loop - need a closure?
for i = 1 to 5
{
var el = document.createElement('img');
el.ondblclick = somefunction();
mydiv.appendChild(el);
}
似乎el.ondblclick = somefunction('test');不做任何插入。
我知道我可以做..
el.ondblclick= function() { somefunction('test') };
..但这在循环中不起作用!
答案 0 :(得分:3)
你的语法错了。
for (var i = 1; i <= 5; i++) // initialization, condition, loop step
{
var el = document.createElement('img');
// you do not want to call `somefunction`, but refer to it:
el.ondblclick = somefunction;
mydiv.appendChild(el);
}
如果您的问题是,您希望在回调函数中使用i
:
for (var i = 1; i <= 5; i++)
{
var el = document.createElement('img');
el.ondblclick = (function(i) { // bind i
return function() { // return closure
toggleClass('svg_container_' + i);
};
})(i);
mydiv.appendChild(el);
}
C.f。
答案 1 :(得分:0)
这是最终的代码。当人们不发布一个有效的例子时,我个人很讨厌
var sCurMonthId = sMonthId.substr(4, 2);
var cellRight = oCurRow.insertCell(-1);
cellRight.colSpan = iNumCells;
for (svg = 1; svg < iNumCells; svg++)
{
var div = document.createElement('div');
div.className = 'svg_container';
div.id = 'svg_container_'+svg+'_'+sMonthId;
cellRight.appendChild(div);
var el = document.createElement('img');
el.style.width = svg == 5 ? '99.5%' : '49%';
el.className = 'svg_chart';
el.style.cssFloat = svg%2 == 0 ? 'right' : 'left';
el.ondblclick = (function(svg) {
return function() {
toggleClass('svg_container_'+svg+'_'+sMonthId, 'svg_container', 'svg_expanded');
};
})(svg);
el.src = 'mySite.tld';
div.appendChild(el);
}