【问题标题】:Why JQuery click event changes all images on page?为什么 JQuery 点击事件会改变页面上的所有图像?
【发布时间】:2011-09-08 22:32:55
【问题描述】:

我有一个产品页面,其中包含图像缩略图以及用于更改缩略图的封面和封底链接。问题是,当您单击这些链接以更改缩略图时,其余产品缩略图的所有图像也会更改。
如何将点击事件绑定到该产品,以便仅更改缩略图?

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;
  });

希望有人能引导我朝着正确的方向前进。谢谢。

【问题讨论】:

标签: jquery click


【解决方案1】:

$('.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;
  });

【讨论】:

  • 谢谢!这完美地工作。我在这个问题上已经两天了,现在很清楚了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
  • 2013-09-03
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多