Javascript将变量传递给事件函数

Gue*_*ser 0 javascript

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

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

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

由于某种原因,即使我在数字39处,在我附加的函数中传递的i的值是i的最终值,即80.

sle*_*man 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.
};
Run Code Online (Sandbox Code Playgroud)

但是,请记住这是一个关闭.所以也许下面的场景是让你沮丧的:

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";
Run Code Online (Sandbox Code Playgroud)

这是循环问题中的经典闭包.看看这个是为了解发生了什么:请解释在循环中使用JavaScript闭包