我有一个产品页面,其中包含图像缩略图和前后盖和后盖的链接以更改缩略图。问题是,当您单击这些链接以更改缩略图时,其余产品缩略图的所有图像也会发生变化。
如何将click事件绑定到该产品,以便仅更改该缩略图?
This is my HTML (this list is repeated bellow for other products with different images):
<div class="product-main-image">
// Here I have the thumb image
<a href="Images/cards/us-sip-connect-5-front-hi-res.jpg" class="product-main-image-hover">
<img src="Images/cards/us-sip-connect-5-front.jpg" class="product-image" />
</a>
// When I click front or back links it's changing all the thumbs for other product as well.
<ul class="thumbs">
<li><a href="Images/cards/front.jpg" rel="Images/cards/front-hi-res.jpg">Front</a></li>
<li><a href="Images/cards/back.jpg" rel="Images/cards/back-hi-res.jpg">Back</a></li>
</ul>
</div>
This is the jQuery:
$('.thumbs a').live('click', function(){
// Get the thumb image tag attributes
var image_thumb = $(this).attr("href");
var image_hi_res = $(this).attr("rel");
// switch the image by removing the node and re-writing in the neccessary HTML
$('.product-main-image-hover').remove();
$('.product-main-image').append('<a href="' + image_hi_res + '" class="product-main-image-hover"><img src="' + image_thumb + '" class="product-image" /></a>');
return false;
});
希望有人能带领我朝着正确的方向前进。感谢。
答案 0 :(得分:0)
$('.product-main-image-hover')
将选择具有该类的所有元素。因此,remove
方法将删除页面上的所有元素。您需要在当前产品中基本找到它。您可以使用jQuery closest
方法查找产品图像容器,然后找到所需的元素并删除。 append
会在元素的末尾添加元素,因此在这种情况下,您必须使用prepend
,因为您必须在同一位置替换图像。
$('.thumbs a').live('click', function(){
// Get the thumb image tag attributes
var image_thumb = $(this).attr("href");
var image_hi_res = $(this).attr("rel");
var productMainImage = $(this).closest('.product-main-image');
// switch the image by removing the node and re-writing in the neccessary HTML
productMainImage.find('.product-main-image-hover').remove();
productMainImage.prepend('<a href="' + image_hi_res + '" class="product-main-image-hover"><img src="' + image_thumb + '" class="product-image" /></a>');
return false;
});