On Mar 6, 8:54 am, jman <erjdri...@gmail.comwrote:
for ( var i = 0; i < div.firstChild.childNodes.length; ++i )
{
var marker = new Object();
marker.iii = i;
sys.addListener( marker, "click", function()
{
alert(marker.iii);
});
}
looks like when clicked - marker object has the value of the last
object thru the loop.
i'd like it to display the appropriate iii value.
JavaScript has function level scoping as opposed to block level (like
other languages). Your marker object is visible across iterations and
the closure will always reference the last instance of the marker
object. I believe you could stop this from happening using a self-
executing anonymous function, like so:
for ( var i = 0; i < div.firstChild.childNodes.length; ++i )
{
(function() {
var marker = new Object();
marker.iii = i;
sys.addListener( marker, "click", function()
{
alert(marker.iii);
});
})(); /* These brackets are necessary to execute the anonymous
function */
}
This should scope the marker inside the anonymous function and the
closure should behave the way you want.