0

我无法将 i 的值传递给 scMotion 函数

for ( i = 0; i < tmp.length; i++ ) {
document.getElementById("sc"+i).onmousedown=function() { return scMotion(i,'up') };
}

为了澄清这个问题,这个 for 循环正在做其他事情,向 dom 添加元素。

出于某种原因,即使 i 的编号为 39,在附加的函数中传递的 i 的值也是 i 的最终值,即 80。

4

2 回答 2

6

i这在您键入时起作用,因为和函数之间应该有一个闭包:

var i="4";
document.getElementById("sc"+i).onmousedown=function() {
    return scMotion(i,'up'); // <-- due to the created closure, the i here
                             //     refers to the i above.
};

但是,请记住这是一个闭包。所以也许下面的场景是什么让你绊倒:

var i="4";
document.getElementById("sc"+i).onmousedown=function() {
    return scMotion(i,'up'); // <-- due to the created closure, the i here
                             //     refers to the i above.
                             //     However, when the event happens in the
                             //     future the value of i in here will
                             //     be "5" due to the code below:
};
i = "5";

这是一个经典的循环闭包问题。请参阅此内容以了解发生了什么:请解释在循环中使用 JavaScript 闭包

于 2012-11-23T11:32:40.333 回答
0

尝试改用 addEventListener。您可以使用 id 将数字传递给您的函数。

for ( i = 0; i < tmp.length; i++ ) {

    var el = document.getElementById( "sc" + i );

    if ( el.addEventListener ) {

        el.addEventListener( 'mousedown', handleMouseDown ); 

    } else if ( el.attachEvent )  { // for IE8 and previous versions

        el.attachEvent( 'mousedown', handleMouseDown );

    }
}

function handleMouseDown( event ) {

    var num = event.target.id.replace( "sc", "" );
    scMotion( num, 'up' );
}
于 2012-11-23T11:44:43.823 回答