2014-10-09 68 views
0

我想改變匹配條件的圖像src。它正在更改頁面上的兩個圖像的第一個正確的src。任何人都可以解釋爲什麼第二個圖像沒有改變?謝謝。更改Img src。只有一個圖像更新

HTML:

<div class="columns large-4 extraImageVer2"> 
    <img src="?Action=thumbnail&amp;Width=600&amp;algorithm=fill_proportional" /> 
</div> 
<div class="columns large-4 extraImageVer2"> 
    <img src="?Action=thumbnail&amp;Width=600&amp;algorithm=fill_proportional" /> 
</div> 

的jQuery:

$(".extraImageVer2 img").each(function() { 
    var imgValue = $(".extraImageVer2").find("img").attr("src"); 
    if (imgValue === "?Action=thumbnail&Width=600&algorithm=fill_proportional") { 
     $(this).attr('src', 'http://placehold.it/600x300'); 
    } 
}); 

的jsfiddle:http://jsfiddle.net/phorden/9wz4rnwf/

+3

那是因爲你」總是選擇裏面的第一個圖像「每個」塊。用這個」。 – 2014-10-09 17:22:15

回答

4

因爲你imgValue值不正確。 .find()搜索後代。您已經選擇的圖像,所以你需要這樣的:

var imgValue = $(this).attr("src"); 

,而不是你現在擁有的一切:

var imgValue = $(".extraImageVer2").find("img").attr("src"); 

jsFiddle example

+0

這是有道理的。感謝您的幫助。 – Phorden 2014-10-09 17:27:35

0

jsFiddle Demo

$(".extraImageVer2 img").each(function() { 
    var imgValue = $(this).attr("src"); 
    if (imgValue === "?Action=thumbnail&Width=600&algorithm=fill_proportional") { 
     $(this).attr('src', 'http://placehold.it/600x300'); 
    } 
});