Javascript关闭问题 [英] Javascript Closure Problem
本文介绍了Javascript关闭问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这种问题被问到了很多,但是我还是找不到一个方法使这项工作正常。
I know this kind of question gets asked alot, but I still haven't been able to find a way to make this work correctly.
代码: / p>
The code:
function doStuff () {
for (var i = 0; i< elementsList.length; i++) {
elementsList[i].previousSibling.lastChild.addEventListener("click", function(){
toggle(elementsList[i])}, false);
}
} // ends function
function toggle (element) {
alert (element);
}
问题是将变量传递给切换函数。它使用this关键字(但是发送一个引用到被点击的项目,在这种情况下是无用的),而不是与在Firefox中警告为未定义的elementsList [i]。
The problem is in passing variables to the toggle function. It works with the this keyword (but that sends a reference to the clicked item, which in this case is useless), but not with elementsList[i] which alerts as undefined in Firefox.
根据我的理解,使用匿名函数调用函数就足以处理闭包问题了,那么我错过了什么?
As I understood it, using anonymous functions to call a function is enough to deal with closure problems, so what have I missed?
推荐答案
Try:
function startOfFunction() {
for (var i = 0; i< elementsList.length; i++) {
elementsList[i].previousSibling.lastChild.addEventListener(
"click",
(function(el){return function(){toggle(el);};})(elementsList[i]),
false
);
}
} // ends function
function toggle (element) {
alert (element);
}
这篇关于Javascript关闭问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文