为什么此代码在单击时将 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>
我需要添加另一个循环吗?我很困惑。谢谢。
最佳答案
回调中的
i
与您递增的 i
相同。当这些回调函数被触发时,i
的值将为 8
,因此所有回调都将添加相同的类。
通常避免在循环中创建事件处理程序。一次选择这些元素并向所有元素添加一个事件处理程序要容易得多:
$('h2').click(function() {
$(this).addClass('hello' + this.id);
});
关于javascript - 遍历元素并添加索引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17627300/