Jquery上一个和下一个按钮被添加到.delegate事件中

时间:2012-07-05 06:24:44

标签: jquery html

这是html,看起来任何人都可以帮我解决如何将next和prev按钮添加到更大的图像。请帮帮我。

JS:

jQuery(function($) {
    $('#thumbs').delegate('img','click', function(){
        var src = this.src.replace('thumb', 'large');
        $("#largeImage").fadeOut(function() {
            this.src = src;
            $(this).fadeIn();
        });
    });
});

HTML:

<div id="page">

  <div id="gallery">

    <div id="panel">
      <img id="largeImage" src="images/image_01_large.jpg" />
    </div>

    <div id="thumbs">
        <img src="images/image_01_thumb.jpg" alt="1st image description" />
        <img src="images/image_02_thumb.jpg" alt="2nd image description" />
        <img src="images/image_03_thumb.jpg" alt="3rd image description" />
        <img src="images/image_04_thumb.jpg" alt="4th image description" />
        <img src="images/image_05_thumb.jpg" alt="5th image description" />
    </div>

  </div>

  <a href="#" id="next">Next</a>
  <br />
  <a href="#" id="prev">Prev</a>

</div>

1 个答案:

答案 0 :(得分:0)

如果不过多地更改代码,这应该可行。关于这项工作有两点需要注意:

  1. 活动缩略图的类别为“活动”。因此,我们可以轻松跟踪当前正在显示的较大图像。
  2. 它依赖于你保持next和prev标签的id被命名为“next”和“prev”,它们用于调用获取下一个和前一个DOM元素的相应jQuery函数。

        
            
                
            

        <div id="thumbs">
            <img class="active" src="images/image_01_thumb.jpg" alt="1st image description" />
            <img src="images/image_02_thumb.jpg" alt="2nd image description" />
            <img src="images/image_03_thumb.jpg" alt="3rd image description" />
            <img src="images/image_04_thumb.jpg" alt="4th image description" />
            <img src="images/image_05_thumb.jpg" alt="5th image description" />     
        </div> 
    </div> 
    <div id="gallery-nav">
        <a href="#" id="next">Next</a> <br /> <a href="#" id="prev">Prev</a>
    </div>
    

      $(function(){
      var thumbs = $('#thumbs'),
          largeImage = $('#largeImage');
    
      thumbs.delegate('img','click', function(){
          var $this = $(this).addClass('active'),
              src = $(this).attr('src').replace('thumb', 'large');
    
          thumbs.find('.active').removeClass('active');
    
          largeImage.fadeOut(function() {
              this.src = src;
              $(this).fadeIn();
          });
      });
    
      $('#gallery-nav a').click(function() {
          var type = $(this).attr('id'),
              thumbImages = thumbs.find('img'),
              next = thumbImages.filter('.active')
                      .removeClass('active')[type]();
    
            if(!next.length) {
                next = type === 'next' ? thumbImages.filter(':first-child') : thumbs.find(':last-child');
            }
    
            var src = next.attr('src').replace('thumb', 'large');
    
          largeImage.attr('src', src);
          next.addClass('active');
      });
    
      });