Thursday, 15 June 2017

javascript - Adding a different onclick for each div with one loop


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 {

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;




 


















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{

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]};

}
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...