<body>
<div id="links">
</div>
</body>
<script type="text/javascript">
var A = function(j) {
this.b = j;
};
var links = $("#links");
for (var i = 0; i < 100; i++) {
var a = new A(i); // a is the local variable mentioned in the question
links.append($("<a> " + i + " </a>").click(function() {
console.log(a.b);
// when the <a>i</a> is clicked 99 is always printed to console
}));
}
</script>
In this above script when, say, <a>45</a>
is clicked, i thought 45 will be printed, but instead 99 is printed. No matter what link is clicked, 99 is always printed. I thought a being accessed inside console.log()
will point to the local a that was created in that particular loop, and so would print the corresponding value of i. Why is this happening? Am I doing something wrong?
Anyway, now I need it such that when the links are clicked, their corresponding objects are acted upon, not the object that was created last. How will I achieve this?