2013-07-13 92 views
0

爲什麼此代碼在點擊後會將class=hello5添加到所有h2元素?有4個h2元素。遍歷元素並添加索引號

for (i=0; i < $('h2').length; i++) { 
    $('#' + i).click(function(index) { 
    $(this).addClass('hello' + i) 
    }) 
}; 

我希望它添加class=hello0class=hello1

HTML:

<h2 id="0">0</h2> 
<h2 id="1">1</h2> 
<h2 id="2">2</h2> 
<h2 id="3">3</h2> 

我一定要添加另一個循環?我很困惑。謝謝。

+0

元素ID不數值開始。 – ravisoni

+2

@ravisoni:它可以在HTML5中。 – Blender

+0

@aaa檢查答案和工作小提琴 – ravisoni

回答

2

i在回調是,你遞增相同i。當這些回調函數被觸發時,i的值將是8,所以所有的回調函數都會添加相同的類。

避免在循環中創建事件處理程序。這是很容易,只是一次選擇這些元素,並添加一個單一事件處理所有的人:

$('h2').click(function() { 
    $(this).addClass('hello' + this.id); 
}); 

Demo on jsfiddle

1

主要問題是,您期待處理程序的參數作爲索引,但它不是,它是eventObject。

您更好地使用。每()函數是這樣的:

$("h2").each(function(index, item){ 
    $(item).click(function(e){ 
     e.preventDefault(); 
     $(this).addClass("hello" + index); 
    }) 
}) 
+0

你可以做'$('h2')。addClass(function(i){return'hello'+ i;});',但是當元素不會觸發被點擊。 – Blender

+0

謝謝你的評論。我錯過了OP需要點擊添加類。而我不知道我可以用這種方式使用addClass。 –

0

我編輯你的HTML片段:

<h2 id="id0">0</h2> 
<h2 id="id1">1</h2> 
<h2 id="id2">2</h2> 
<h2 id="id3">3</h2> 

試試這個代碼:

$('h2[id^="id"]').click(function(index){ 
    var idx = $(this).index(); 
    $(this).addClass('hello' + idx) 
}); 

Fiddle here

0

由於時間點擊事件在很火。變量i是完成循環,它會得到值4.解決方案是使用必須得到索引h2元素並分配給類。我有一點點的變化:

$().ready(function() { 
    for (i = 0; i < $('h2').length; i++) { 
     $('#' + i).click(function (index) { 
      $(this).addClass('hello' +$("h2").index($(this))) 
     }) 
    }; 
}) 

Demo on jsfiddle