I have the following code:
$(document).ready(function() {
var $body = $("body");
for (var i = 0; i < 10; i++)
{
var $a = $("<a>");
$body.append($a);
$a.text(i);
$a.click(function() {
alert(i);
});
}
});
Clicking on any of the anchors will alert the number 10, when I’d of expected it to alert the value of i of when the function was created.
To get it working, I’ve just used data to append the ID to the anchor and I retrieve it within the function, but this just seems really messy. Why can I not specify the value when the function was created?
You could use the
jQuery.each()[docs] method and keep your code a little cleaner.