jQuery:如何遍历所有’a’元素?

我希望能够更改页面上所有锚点的属性。 但我不知道如何遍历所有这些。

使用每个:

http://api.jquery.com/each/

$("a").each(function(){ //do something with the element here. }); 

您可以将.attr()与函数一起使用来更改特定属性,例如:

 $("a").attr("href", function(i, oldHref) { return oldHref + "#hash"; }); 

这比.each()便宜,因为你不是在每次迭代中创建一个额外的jQuery对象,而是在没有这样做的情况下访问DOM元素上的属性。

jQuery本身就提供了这种能力。

 $('a').do_something(); 

do_something()传递给页面上的每个a 。 所以:

 $('a').addClass('fresh'); // adds "fresh" class to every link. 

如果你想要做的事情需要单独查看每个a的属性,那么使用.each()

 $('a').each( function(){ var hasfoo = $(this).hasClass('foo'); // does it have foo class? var newclass = hasfoo ? 'bar' : 'baz'; $(this).addClass(newclass); // conditionally add another class }); 
 $('a').each(function(i){ $(this).attr('href','xyz'); }); 

您可以使用jQuery .each()来实现此目的:

 $('a').each(function() { // The $(this) jQuery object wraps an instance // of an anchor element. });