2013-03-03 40 views
0

代碼是這樣的:保持當前的src ATTR所以我可以檢索圖像

$(' html body div.wrapper div.middle div.post_home:first-child a ').hover(
function() { 
     $(' html body div.wrapper div.middle div.post_home:first-child a > img ').attr("src", "http:/site/test1.png"); 
}, 
function() { 
     $('html body div.wrapper div.middle div.post_home:first-child a > img ').attr("src", "currentSrc"); 
}); 

我只需要保持改變之前的圖像的src值,以便在鼠標離開我可以檢索並顯示圖像。

+1

(一)你也許可以忽略一些標籤/從你選擇的類(比如' html'和'body'),因爲它們不會爲選擇器添加任何特異性。 (b)在事件處理程序中,可以使用'this'來引用元素(即'$(this)'),不必再使用選擇器。 (c)對simper代碼感到高興:) – 2013-03-03 23:22:32

+0

首先,你的選擇器是矯枉過正的。 '$('div.post_home:first-child a')'應該可以做到。存儲事物的一個好方法是使用html5數據屬性:'$(this).data('src')'。 – slamborne 2013-03-03 23:24:12

+0

http://stackoverflow.com/a/15192185/1250044 – yckart 2013-03-03 23:26:16

回答

1

備份您src在你的事件改變之前開始attrivute。當你想回去時使用它。

var currentSrc; 
$('.post_home:first-child a ').hover(function() { 

    currentSrc = $('.post_home:first-child a > img').attr("src"); 
    $('.post_home:first-child a > img ').attr("src", "http:/site/test1.png"); 

}, function() { 

     $('.post_home:first-child a > img').attr("src", currentSrc); 

}); 

注:我編輯你的選擇,因爲你所擁有的是超過必要的。

+0

謝謝你清除我的代碼。我在做同樣的事情,但我的錯誤是在attr方法中的變量currentSrc中使用引號。 – mt0s 2013-03-03 23:35:30

0

您可以將原始src緩存在一個變量中以便稍後使用它。事情是這樣的:

var originalSrc = $(' html body div.wrapper div.middle div.post_home:first-child a > img ').attr('src'); 
$(' html body div.wrapper div.middle div.post_home:first-child a ').hover(
function() { 
     $(' html body div.wrapper div.middle div.post_home:first-child a > img ').attr("src", "http:/site/test1.png"); 
}, 
function() { 
     $('html body div.wrapper div.middle div.post_home:first-child a > img ').attr("src", originalSrc); 
}); 
0

嘗試使用HTML5 data attributes,因此您可以將原始網址存儲在「src」道具中,並在您要更改的圖像中存儲data-src="my other image"

<img src="my original image" data-src="my other src" /> 
1

您可以使用data屬性來存儲你的src後來檢索:

var thisImg; 
$('.post_home:first-child a').hover(function() { 
    thisImg = $('img', this)[0]; 
    $(this).data('img-src', thisImg.src); 
    thisImg.src = "http:/site/test1.png"; 
}, function() { 
    thisImg.src = $(this).data('img-src'); 
}); 

Demo

+0

再次歡呼@roXon :) – 3dgoo 2013-03-04 00:15:43

+0

(+ 1'd)或者如果你喜歡更多(我喜歡它:) http://jsfiddle.net/H2uc3/5/ – 2013-03-04 00:20:18

相關問題