2009-10-26 77 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