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!
Edit:
The solution is to use jQuery.data to associate arbitrary data with each element:
<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.data('nr', nr);
li.click(function() {
alert($(this).data('nr'));
});
$('ul').append(li);
}
});
</script>
</head>
<body>
<ul>
</ul>
</body>
</html>