使用一个循环为每个div添加不同的onclick [英] Adding a different onclick for each div with one loop
问题描述
可能重复:
JavaScript不支持使用局部变量的闭包吗?
我想用1个循环动态地为我的div元素添加一个不同的onclick。
这是我的代码的简化版。
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};
}
}
我想要点击每个div显示newtxt [i]。让我感到困惑的是,我的div会逐渐改变颜色,但是onclick只会影响最后一个div。如果我点击div 0或div 1,它只会改变div2的内部html,而不是每一个。
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];};
}
这样做是有效的,但我需要在循环中这样做我不必为每组div创建数十个函数,这不是DRY。
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.
这里是我的html,风格为#mydiv div- height:50px ;宽度:200像素;边框:1px纯黑色;
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>
感谢您的回答,对不起,如果我的措辞有点令人困惑。
tl;博士我想为一组带有1个循环的div添加单独的onclick
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
编辑以获得更清晰*
解决方案
指定 di = i ,并使用此问题已解决。
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]};
}
}
推荐答案
试试这个
d.onclick=function(){this.innerHTML=this.style.backgroundColor};
这篇关于使用一个循环为每个div添加不同的onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!