为什么此代码在点击后会将class=hello5
添加到所有h2元素?有4个h2元素。遍历元素并添加索引号
for (i=0; i < $('h2').length; i++) {
$('#' + i).click(function(index) {
$(this).addClass('hello' + i)
})
};
我希望它添加class=hello0
,class=hello1
等
HTML:
<h2 id="0">0</h2>
<h2 id="1">1</h2>
<h2 id="2">2</h2>
<h2 id="3">3</h2>
我一定要添加另一个循环?我很困惑。谢谢。
元素ID不数值开始。 – ravisoni
@ravisoni:它可以在HTML5中。 – Blender
@aaa检查答案和工作小提琴 – ravisoni