爲什麼此代碼在點擊後會將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