jQuery: how do I loop through all 'a' elements?

I want to be able to change all the anchor's properties on a page. But I don't know how to loop through all of them.

12
задан NullVoxPopuli 31 August 2010 в 15:34
поделиться

3 ответа

используйте каждый:

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

$("a").each(function(){
    //do something with the element here.
});
24
ответ дан 2 December 2019 в 03:22
поделиться

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
});
6
ответ дан 2 December 2019 в 03:22
поделиться
$('a').each(function(i){
    $(this).attr('href','xyz');
});
3
ответ дан 2 December 2019 в 03:22
поделиться
Другие вопросы по тегам:

Похожие вопросы: