-1

可能重复:
Javascript 循环中的事件处理程序 - 需要闭包吗?

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') };

..但这在循环中不起作用!

4

2 回答 2

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);
}

比照

于 2012-11-09T19:24:10.880 回答
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);
        }
于 2012-11-09T20:03:08.067 回答