2011-03-26 93 views
2

剛敲了一個形象切換,並且遇到了一個小問題來了:jQuery的查找特定的IMG ATTR(SRC)

我有隱藏的三幅圖像,並懸停在相應的縮略圖時,我想添加類的電流到主圖像(以阻止它被隱藏)。

$("#thumbs img").mouseenter(function(){ 

//this gets the url of the thumb 
var imgSrc = $(this).attr("src"); 
//this removes the last 7 letters 
imgSrc = imgSrc.slice(0,-7); 
//this adds .jpg to the end 
imgSrc = imgSrc + '.jpg'; 

//This removes all images class of current 
$('#mainImg img').removeClass("current"); 

//I want this to find the image with the src of imgSrc and add the current class 
$('#mainImg').find(img.attr("src",imgSrc)).addClass("current"); 

最後一行是問題,它不起作用 - 有什麼建議嗎?

回答

7

您需要遍歷圖像,並找到一個具有正確源。你可以通過改變你的最後一行下面這樣做:

$('#mainImg img').each(function(i,ele){ 
    if ($(this).attr("src") == imgSrc) { $(this).addClass("current"); } 
} 
+0

幾秒打我笑 – corroded 2011-03-26 17:36:26

0
$('#image'+$(this).attr('id')).addClass("current"); 

試着給你的圖片ID「圖像1」,「圖像2」,等你的縮略圖ID「1」,「2」,」 3' 。那麼這應該工作。你必須通過所有圖片迭代來完成你想用你的代碼是什麼。

0

你試圖尋找IMG這不是一個變量。你應該做的是這樣的:

$("#mainImg img").each() 

... 
loop through the images and check which one has the correct source then add the class to it 

但我確實認爲這是有點超過頂部。你能給我們一個示例代碼來處理嗎?您在源獲取圖像的過程不是一個好主意,我認爲