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

Nul*_*uli 12 jquery

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

Kea*_*her 24

使用每个:

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

$("a").each(function(){
    //do something with the element here.
});
Run Code Online (Sandbox Code Playgroud)

  • akellehe提到的"元素"是通过函数内部的`this`关键字引用的. (6认同)

Nic*_*ver 11

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

$("a").attr("href", function(i, oldHref) {
  return oldHref + "#hash";
});
Run Code Online (Sandbox Code Playgroud)

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


Ken*_*ler 6

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

$('a').do_something();
Run Code Online (Sandbox Code Playgroud)

将在页面上的do_something()每一个a.所以:

$('a').addClass('fresh'); // adds "fresh" class to every link.
Run Code Online (Sandbox Code Playgroud)

如果您想要做的事情需要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
});
Run Code Online (Sandbox Code Playgroud)