2010-08-31 89 views

回答

22

使用:

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

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

akellehe提到的「元素」是通過函數內的'this'關鍵字引用的。 – 2010-08-31 15:43:11

6

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 
}); 
3
$('a').each(function(i){ 
    $(this).attr('href','xyz'); 
}); 
0

您可以使用jQuery .each()用於此目的:

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

您可以使用.attr()函數N到改變一個特定的屬性,例如:

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

這是價格比.each(),因爲你沒有創造每個迭代內的額外的jQuery對象,你所訪問的DOM元素的屬性,而無需這樣做。

+1

+1更便宜的實現 – 2010-08-31 15:43:57