2014-10-09 53 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'); 
    } 
});