2010-08-21 49 views
3

這是我到目前爲止有:jQuery的addclass每個WordPress的圖像後

<script> 
$(document).ready(function(){ 
    $(".entry-content img:first").addClass('postimage'); 
}); 
</script> 

正如你所看到的,對於.entry內容第一圖像它增加了我的課。很酷,工作正常。 Uncool,它不適用於每個帖子,但只在頁面上的第一個帖子。

我不知道如何解決這個問題。我是否需要以某種方式使用.each,或者我有什麼問題?

感謝

+0

你能向我們展示了一下您的標記嗎? – roosteronacid 2010-08-21 09:09:05

回答

1

這是因爲CSS選擇器選擇第一.entry-content img,而不是在每一個.entry-content第一img。這關乎運營商的優先權。

不過,您可以遍歷每個.entry-content並手動選擇該節點中的img:first

$(document).ready(function(){ 
    var entries = document.querySelectorAll('.entry-content'); 
    for (var i = 0; i < entries.length; i++) { 
     var firstImage = $(entries[i].querySelectorAll('img:first')[0]); 
     firstImage.addClass('postImage'); 
    } 
}); 
+0

所以它會是$(「img:first .entry-content」)? – 2010-08-21 08:17:48

+0

不會。這會選擇第一個「img」中的所有'.entry-content'節點。其實,我不確定你甚至可以在那裏放置':first'。你需要做的是選擇'.entry-content'。然後你循環遍歷每一個,並選擇裏面的'img:first'。 – 2010-08-21 08:20:51

+0

我只是不確定如何選擇條目內容,然後img:首先爲它的每個實例?那是jq中的另一行嗎? – 2010-08-21 08:27:25

0

這將迭代你的所有帖子,並將類應用到每個的第一個圖像。

$.each('.entry-content', function() { 
    $(this).find('img:first').addClass('postImage'); 
}); 
0

保羅Dragoonis'回答的一個變化:

$(".entry-content").each(function() 
{ 
    $("img:first", this).addClass("postImage"); 
});