Jquery找到特定的img attr(src)

时间:2011-03-26 17:31:43

标签: jquery image

刚刚敲了一个图像切换器,遇到了一个小问题:

我隐藏了三个图像,当鼠标悬停在相关缩略图上时,我想将当前类添加到主图像中(以阻止它被隐藏)。

$("#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");

最后一行是问题,它不起作用 - 有什么建议吗?

3 个答案:

答案 0 :(得分:7)

您需要迭代图像并找到具有正确来源的图像。您可以通过将最后一行更改为以下内容来完成此操作:

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

答案 1 :(得分:0)

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

尝试将图片ID设为'image1','image2'等,缩略图ID为'1','2','3'。然后这应该工作。你必须遍历所有图像才能用你的代码完成你想要的东西。

答案 2 :(得分:0)

你正试图寻找不是变量的img。你应该做的是这样的事情:

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

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

但我确实认为这有点过头了。你能给我们一个示例代码吗?你从源头获取图像的过程并不是我认为的好主意