简体   繁体   中英

How do I make the click function on my carousel work when items are appended?

I have a (very raw) test site up at http://belmontfeed.com/site/ where I am trying to get the vertical carousel on the right to control the photo on the left.

The Previous/Next buttons work fine, and generally clicking on a carousel item will load the photo associated with it, but whenever I allowWrap on the carousel the click no longer functions.

I believe it is because the appending/prepending messes up the count that the click function is based off of, but I am fairly new to jQuery and am not sure where to turn.

The complete code should be viewable on the above site. Any help would be much appreciated!

if ( opts.allowWrap !== false ) {
  // prepend and append extra slides so we don't see any empty space when we
  // near the end of the carousel.  for fluid containers, add even more clones
  // so there is plenty to fill the screen
  // @todo: optimize this based on slide sizes
  opts.slides.slice(0, opts.slideCount).clone().css( slideCSS ).appendTo( wrap );
  if ( opts.carouselVisible === undefined )
     opts.slides.slice(0, opts.slideCount).clone().css( slideCSS ).appendTo( wrap );
  opts.slides.slice(0, opts.slideCount).clone().css( slideCSS ).prependTo( wrap );
  if ( opts.carouselVisible === undefined )
     opts.slides.slice(0, opts.slideCount).clone().css( slideCSS ).prependTo( wrap );

  wrap.find('.cycle-slide-active').removeClass('cycle-slide-active');
  opts.slides.eq(opts.startingSlide).addClass('cycle-slide-active');
}

UPDATE: The most direct click function code is as follows:

$('#cycle-2 .cycle-slide').click(function(){ 
    var index = ($('#cycle-2').data('cycle.API').getSlideIndex(this)-8);   
    slideshows.cycle('goto', index); 
}); 

I added a ghetto fix of just subtracting the count by 8 (as that is the number of prepends) but it stops functioning once it reaches number 8 until it auto rotates back to one. A more sustainable fix would be lovely...

Using the new spec for jquery, you can call

$(document).on('click', '.cycle-carousel-wrap > div', function(e) {...});

This way, jquery finds the object each time, regardless of whether it's been modified/appended/etc.

Hope this helps!

Fixed it! By taking my quick fix and switching the operator from '-' to '%,' I was able to achieve the results I wanted. To set it to a dynamic number I will just swap the eight out for a variable representing the number of looped posts.

$('#cycle-2 .cycle-slide').click(function(){ 
    var index = ($('#cycle-2').data('cycle.API').getSlideIndex(this)%8);   
    slideshows.cycle('goto', index); 
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM