You need to save a copy of this variable, for example:
for (aTag in tagList) { if (tagList.hasOwnProperty(aTag)) { nextTag = $('<a href="#"></a>'); nextTag.text(aTag); var laTag = aTag; nextTag.click(function() { alert(laTag); }); $('#mydiv').append(nextTag); $('#mydiv').append(' '); } }
The aTag variable changes every time you execute a loop, at the end of the loop it remains as the last element in the loop. However, each of the functions you create points to this same variable. Instead, you need the per variable, so make a local copy like mine above.
You can also shorten this with chaining, but I feel that in this case it is cloudy because the problem is with reach and links.
source share