[Javascript] looped var

Steve Clay sclay at ufl.edu
Thu Apr 20 10:00:32 CDT 2006


Thursday, April 20, 2006, 10:21:25 AM, Cutter (JSRelated) wrote:
> for (var intI = 0 ; intI < 10 ; intI++){
> var objA = document.createElement( "div" );

Place one "var objA;" before the loop then remove the "var" inside.
Redeclaring a variable is a bad practice that will bite you in other
languages. 

> objA.onclick = function(){ alert( intI ); };

It's doing its job, it's alerting the value of intI, which is what you left
it. The easiest solution is to add a custom property to the object to hold
the current value of intI:

objA.currentI = intI;
objA.onclick = function(){ alert( this.currentI ); };

Steve
-- 
http://mrclay.org/




More information about the Javascript mailing list