jQuery:如何循环所有';a';元素?

jQuery:如何循环所有';a';元素?,jquery,Jquery,我希望能够更改页面上所有锚的属性。但我不知道如何循环使用所有这些选项。使用每个选项: jQuery天生就提供了这种能力 $('a').do_something(); 将do_something()发送到页面上的每个a。因此: $('a').addClass('fresh'); // adds "fresh" class to every link. 如果要执行的操作需要单独查看每个a的属性,请使用: 您可以将jQuery用于此目的: $('a').each(function() {

我希望能够更改页面上所有锚的属性。但我不知道如何循环使用所有这些选项。

使用每个选项:


jQuery天生就提供了这种能力

$('a').do_something();
do_something()
发送到页面上的每个
a
。因此:

$('a').addClass('fresh'); // adds "fresh" class to every link.
如果要执行的操作需要单独查看每个
a
的属性,请使用:

您可以将jQuery用于此目的:

$('a').each(function() {   
 // The $(this) jQuery object wraps an instance  
 // of an anchor element.  
});
可以与函数一起使用来更改特定属性,例如:

$("a").attr("href", function(i, oldHref) {
  return oldHref + "#hash";
});
这比在每次迭代中都不创建额外的jQuery对象更便宜,因为您在访问DOM元素的属性时没有这样做。

Akelle提到的“元素”是通过函数中的
This
关键字引用的。
$('a').each(function(i){
    $(this).attr('href','xyz');
});
$('a').each(function() {   
 // The $(this) jQuery object wraps an instance  
 // of an anchor element.  
});
$("a").attr("href", function(i, oldHref) {
  return oldHref + "#hash";
});