This is probably an easy question but I can’t figure out the best answer for it.
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>
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.
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?
You only have one variable
iin an outer scope shared by all your click handlers. You need to create a local variableifor each closure. This will work:Check “The Infamous Loop” problem in this article (and read the whole artice) for more information 🙂