2012-07-24 62 views
0

我得到了下面的代碼:動態改變圖像源 - jQuery的

HTML

<div class="image"> 
    <img src="http://ecx.images-amazon.com/images/I/41ghiuvjdvL._SL75_SS50_.jpg" /> 
</div> 

<br /> 

<div class="photo"> 
    <img src="http://profile.ak.fbcdn.net/hprofile-ak-ash2/27520_119569768054263_2432_q.jpg" /> 
</div>​ 

JS

// getting src of bottom image 
var bottomSrc = $(".photo img").find("src"); 

// getting src of top image 
var topSrc = $(".image img").find("src"); 

$(".photo").click(function() { 
    // changing sources 
    // topSrc.attr("src", bottomSrc); 
    // topSrc.replaceWith(bottomSrc); 
    topSrc.replace(bottomSrc); 
})​ 

Fiddle

當底部圖像被點擊,我想頂部圖像的src被替換成底部圖像的src,這樣兩個圖像都是相同的。

爲什麼提供的代碼不起作用?

+0

要使用'.attr您需要jQuery來獲取和設置src屬性,使用ATTR()函數('SRC ')'獲取src屬性的值,而不是'.find()',它可以找到子元素 – MrOBrian 2012-07-24 23:53:52

回答

4

嘗試了這一點:

$(".photo").click(function() { 
    var src=$(this).children("img").attr("src"); 
    $(".image img").attr("src",src); 
})​;