JavaScript中的事件处理程序作用域
这可能是一个简单的问题,但我想不出最佳答案.
This is probably an easy question but I can't figure out the best answer for it.
我在屏幕上有10个< div>
元素.他们每个人都有一个 click()
事件侦听器:
I have 10 <div>
elements on screen. Each of them has a click()
event listener:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="element0">Click me! (0)</div>
<div id="element1">Click me! (1)</div>
<div id="element2">Click me! (2)</div>
<div id="element3">Click me! (3)</div>
<div id="element4">Click me! (4)</div>
<div id="element5">Click me! (5)</div>
<div id="element6">Click me! (6)</div>
<div id="element7">Click me! (7)</div>
<div id="element8">Click me! (8)</div>
<div id="element9">Click me! (9)</div>
<script type="text/javascript">
for ( var i = 0; i < 10; i++ ) {
var element = document.getElementById( "element" + i );
element.onclick = function () {
alert( "Element " + i );
}
}
</script>
</body>
</html>
但是,每次我单击一个元素时,它都会显示元素10"!似乎所有这些事件处理程序都为 i
使用了相同的值.
But every time I click on an element it says "Element 10"! It seems all those event handlers are using the same value for i
.
我希望它显示"Element N",其中N是当前元素的编号.我不想从元素ID中提取N.我也不想使用jQuery的 data()
方法存储它.我相信必须有一个更简单的解决方案来解决这个问题,但是我找不到它.有人吗?
I want it to show "Element N" where N is the number of the current element. I don't want to extract N from the element id. Neither I want to store it using data()
method of jQuery. I believe there must be a much simpler solution to this problem, but I can't find it. Anyone?
在您所有点击处理程序共享的外部作用域中,您只有一个变量 i
.您需要为每个闭包创建局部变量 i
.这将起作用:
You only have one variable i
in an outer scope shared by all your click handlers. You need to create a local variable i
for each closure. This will work:
for ( var i = 0; i < 10; i++ ) {
var element = document.getElementById( "element" + i );
element.onclick = (function(i){
// returns a new function to be used as an onclick handler
return function () {
alert( "Element " + i );
}
})(i); // Pass in the value of the outer scope i
}
在本文(并阅读整个文章)以获取更多信息:)
Check "The Infamous Loop" problem in this article (and read the whole artice) for more information :)