2010-11-30 84 views
0

在函數循環中,我需要進一步遍歷DOM。

$('.panel_wrapper .panel').each(function(index) { 
    // how can I append to this. For instance another class = "foo" 
    $(this) .foo /* does not work */ 

這與我想要的功能

$(this) = $('.panel_wrapper .panel'); 
$(this) .foo 

下面是一個更好的例子做:

$('.panel-wrapper .panel').each(function(index) { 
    $('.panel-wrapper .panel:eq(' + index + ') .collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});   
}); 

在函數還有額外的操作是將在第一次操作之後但在一個條件語句之後執行,而不是必需的。可以在以下進行:

$('.panel-wrapper .panel').each(function(index) { 
    $(this) ('.collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1}); 
    // conditional statement 
    $(this) /* some other element */ 

}); 
+1

追加什麼?你想添加一個名爲「foo」的CSS類到與你的第一個選擇器相匹配的所有對象嗎?試着在你的問題中更精確。 – 2010-11-30 07:45:56

回答

1

您可以使用.find()功能:

$(this).find('.foo'); 
+0

我沒有添加類或ID的,我試圖追加另一個路徑到目的地。例如,我需要得到第二個李的形象。可能有條件測試需要在第三個圖像中改變不透明度。所以一旦我有$(this)其他邏輯需要執行。 – barryg 2010-11-30 07:58:46

1

要追加一個類,你應該上使用

$(this).addclass("foo") 

它實際上取決於你想要什麼要做 如果你想直接訪問DOM元素本身,你不應該把它包起來

this.foo =... 

將增加foo的DOM元素本身(。每個函數內)

0

你要追加到選擇(即進一步限制選擇的項目)或追加到選擇的項目? @達林的解決方案將做前者;如果您要選擇多個項目,穿越了他們以及可以執行下列操作之一:

$('.panel_wrapper .panel').add('.foo').each(function(index) { 

$('.panel_wrapper .panel, .foo').each(function(index) { 
+0

我剛更新了這個問題。 – barryg 2010-11-30 16:19:12