2010-07-18 27 views
7

$("p")引用當前網頁上的所有段落。是否有可能爲每個匹配選擇器的元素執行代碼?jQuery:執行與選擇器匹配的每個元素的代碼

下面是僞代碼一個簡單的例子:

// Show the background color of every paragraph on the page 
foreach (object = $("p")) { 
    alert(object.css("background-color")); 
} 

回答

9
$('p').css('background-color', 'black') 

如果您需要更多的靈活性:

$('p').each(function() { 
    $(this).css('background-color', 'red'); 
}); 
+0

謝謝,這個作品! – Pieter 2010-07-18 11:34:24

5

可以使用.each()通過匹配的元素進行迭代,就像這樣:

$("p").each(function() { 
    alert($(this).css("background-color")); 
}); 

如果你想設置的東西(例如沒有從上面的每個喜歡的價值),沒有必要.each(),只是執行它,它會運行的每個元素上設置......這是默認的jQuery的行爲,例如:

$("p").show(); //shows all <p> elements 
0

each方法聽起來好像要

$('p').each(function() { 
    alert($(this).css('backgroundColor')); 
} 
什麼
+2

在這裏旁邊,'backgroundColor'可以用作屬性,比如'{backgroundColor:'red',color:'green'}',但是當使用字符串時,除了標準語法之外不需要使用任何東西(在調試時也更容易找到)。 'backgroundColor'在運行時被轉換回''background-color'',不需要在這裏轉換它只是爲了創建額外的工作:) – 2010-07-18 11:07:14

+0

啊,很好,謝謝你的尼克。我習慣這種方式使用它。必須是時候打破這種習慣:-) – 2010-07-18 11:43:23

相關問題