2009-10-26 76 views
0

我有一個帶有9個錨定標記的UL,每個都有'highlight'類。簡單的jQuery。每個問題

這裏是一個JavaScript代碼的使用jQuery:

 var titles = $('a.highlight'); 
     jQuery.each(titles, alert(titles.length)); 

我希望這段代碼做: 警報9倍,數字9

什麼的這段代碼實際上做: 提醒1次數字9.

我在想什麼?

回答

3

jQuery.each調用一個函數,您將它傳遞給它在給定集合中找到的每個項目。您傳遞的是立即評估的表達式。你需要用一個匿名函數的表達式:

jQuery.each(titles, function() { 
    alert(titles.length) 
}); 
-1

我自己是新手,但不應該是titles.each(),而不是jQuery.each()?

+0

你可以使用任何一種方式,jQuery.each只是一個通用的迭代器。 http://docs.jquery.com/Utilities/jQuery.each 無論哪種方式,我都得到了同樣的結果。 – 2009-10-26 01:27:55

+0

我的不好。我以爲你試圖調用$(...)。each()。 – 2009-10-26 01:36:04

0

您正在尋找:

jQuery.each(titles, function(index, title) { 
    console.log('the title at index ', index, ' is ', title); 
}); 

each功能見the documentation