1

Possible Duplicate:
Doesn’t JavaScript support closures with local variables?

I want to add a different onclick dynamically to my div elements with 1 loop. This is a simplified version of my code.

var colors=['blue','green','yellow'];
var newtxt=['box1','box2','box3'];

var i;
function set_element2()
{
var x=document.getElementById('mydiv').getElementsByTagName('div');
  for(i=0;i<x.length;i++)
  {

    var d=x[i];
var col=colors[i];
    var txt=newtxt[i];
d.style.background=col;
d.onclick=function(){d.innerHTML=txt};

  }
}

i want each div when clicked to display newtxt[i]. What is stumping me is the colors change for my divs individually like they should, however the onclick is only affecting the last div. If i click div 0 or div 1 it only changes the inner html of div2 not each one individually.

function wrongway()
{
x[0].onclick=function(){x[0].innerHTML=newtxt[0];};
x[1].onclick=function(){x[1].innerHTML=newtxt[1];};
x[2].onclick=function(){x[2].innerHTML=newtxt[2];};
}

doing it this way works, however I need to do this in a loop so I dont have to create dozens of functions for each set of divs, and this is not DRY.

here is my html with the style of #mydiv div- height:50px; width:200px; border:1px solid black;

 <body>
 <section id='mydiv'>

    <div>
</div>

<div>
</div>

<div>
</div>


 </section>
 <input type='button' onclick='set_element2()'> 
 </body>

thanks for any answers, sorry if my wording is a bit confusing. tl;dr i want to add separate onclicks to a set of divs with 1 loop

editied for more clarity*

solution by specifying d.i=i, and using this the problem is solved.

function multOnclicks()
{
var x=document.getElementById('mydiv').getElementsByTagName('div');
for(i=0;i<x.length;i++)
{

  var d=x[i];
  var col=colors[i];
  var txt=newtxt[i];

  d.style.background=col;

  d.i = i;
  d.onclick=function(){this.innerHTML=newtxt[this.i]};

  }
}
Community
  • 1
  • 1

1 Answers1

0

Try this

d.onclick=function(){this.innerHTML=this.style.backgroundColor};

http://jsfiddle.net/UAvmx/

codingbiz
  • 26,179
  • 8
  • 59
  • 96
  • this did work but I edited my code to further clarify the problem. This answer finds the colors directly I need the innerHTML to display specific text. – Roberto Gonzales Jan 05 '13 at 21:46