用jquery替换多个html实例

时间:2012-11-06 05:48:55

标签: jquery html

HTML:

<div class="slide">
  <div class="left">
    <img src="img-lg.png" class="image1" />
  </div>
  <div class="thumbs">
    <img src="img-sm.png" />
  </div>
</div>

<div class="slide">         
  <div class="left">
    <img src="anotherimg-lg.png" class="image1" />
  </div>
  <div class="thumbs">
    <img src="anotherimg-sm.png" />
  </div>    
</div>

Jquery的:

var originalContent = $('.left').html();
$("div.thumbs img").hover(function(){
  var largesrc = $(this).attr("src").replace("sm","lg");
  $(".left").html('<img src="' + largesrc 
    + '" width="560" height="377" class="largeimage" />');
}, function() {
  $(".left").html(originalContent);
});

我在悬停时用较小的图像替换大图像,然后恢复原始图像。这工作正常,但我无法弄清楚如何让它与多个实例一起工作。

在第二张幻灯片组中,左图像被原始的第一张左图像替换而不是第二张图像。

2 个答案:

答案 0 :(得分:4)

怎么样

$("div.thumbs img").hover(function(){
        $(this).closest('.slide').find('.left img').attr({
            src: this.src.replace("sm","lg"),
            width: 560,
            height: 377,
            'class': 'largeimage'
        });
}, 
function() {
        var img = $(this).closest('.slide').find('.left img');
        img.attr({src: img[0].src.replace("lg","sm")})
        .removeAttr('width height class');
});

在此处交换图像元素的src属性,而不修改dom结构。

DEMO

答案 1 :(得分:0)

$("div.thumbs img").hover(function(){
  var $this = $(this);

  // find the containing .slide, then find .left within that
  var left = $this.closest('.slide').find('.left');

  // store the original content as "data" on `left`, so
  // we can get it easily in the future
  left.data('originalContent', left.html());

  var largesrc = $this.attr("src").replace("sm","lg");
  left.html('<img src="' + largesrc 
    + '" width="560" height="377" class="largeimage" />');
}, function() {
  var $this = $(this);
  var left = $this.closest('.slide').find('.left');

  // fetch the "data" we stored earlier, and restore it
  left.html(left.data('originalContent'));
});

现有示例here