Sticky/static variable references in for loops
Posted
by pthulin
on Stack Overflow
See other posts from Stack Overflow
or by pthulin
Published on 2010-04-03T09:26:45Z
Indexed on
2010/04/03
9:33 UTC
Read the original article
Hit count: 264
JavaScript
|jQuery
In this example I create three buttons 'one' 'two' 'three'. When clicked I want them to alert their number:
<html>
<head>
<script type="application/javascript" src="jquery.js"></script>
<script type="application/javascript">
$(document).ready(function() {
var numbers = ['one', 'two', 'three'];
for (i in numbers) {
var nr = numbers[i];
var li = $('<li>' + nr + '</li>');
li.click(function() {
var newVariable = String(nr);
alert(i); // 2
alert(nr); // three
alert(newVariable); // three
alert(li.html()); // three
});
$('ul').append(li);
}
});
</script>
</head>
<body>
<ul>
</ul>
</body>
</html>
The problem is, when any of these are clicked, the last value of the loop's variables is used, i.e. alert box always says 'three'.
In JavaScript, variables inside for-loops seem to be 'static' in the C language sense. Is there some way to create separate variables for each click function, i.e. not using the same reference?
Thanks!
© Stack Overflow or respective owner