开发者

jQuery slideshow loop fail

开发者 https://www.devze.com 2022-12-20 11:49 出处:网络
I\'ve been trying to implement snook.ca\'s Simplest jQuery Slideshow, but when applied to child elements inside a <ul> instead of a straightforward stack of images. I\'ve successfully got the sl

I've been trying to implement snook.ca's Simplest jQuery Slideshow, but when applied to child elements inside a <ul> instead of a straightforward stack of images. I've successfully got the slideshow rotating through the necessary child elements, but I've run out of know-how when ending the sequence and returning to the beginning.

I'd like the sequence to return to the first <p> child element and continue in an endless loop.

You can see a demo of the slideshow in operation on JS Bin. Apologies for the verbosity of the jQuery code; I'm sure it could be optimized.

For posterity here is the HTML:

<header>
    <nav>
      <ul>
        <li class="current">
          <h3>...</h3>
          <p><img src="#"><span>...<a href="#">...</a></span></p>
        </li>
        <li>
          <h3>...</h3>
          <p><img src="#"><span>...<a href="#">...</a></span></p>
        </li>
        <li>
          <h3>...</h3>
          <p><img src="#"><span>...<a href="#">...</a></span></p>
        </li>
        <li>
          <h3>...</h3>
      开发者_如何学C    <p><img src="#"><span>...<a href="#">...</a></span></p>
        </li>
      </ul>
    </nav>
  </header>

And here is the jQuery:

$('header nav li').not('.current').children('p').hide();
   setInterval(function(){
     $('header nav li.current').children('p').hide()
     .parent('li').removeClass()
     .next('li').addClass('current')
     .children('p').show()
     .end();
   },3000);

Any help you could give would be much appreciated. Cheers.


Just break your chaining after selecting the next li. If there is no next li, the length of the result set will be 0. When that happens, loop back to the beginning. Then, just finish your setup. Here is a revision on your JSBin code that shows it working:

$('header nav li').not('.current').children('p').hide();
setInterval(function(){
  var $next = $('header nav li.current').children('p').hide()
  .parent('li').removeClass()
  .next('li');

  if(!$next.length) $next = $('header nav li:first');

  $next.addClass('current')
  .children('p').show();
},3000);
0

精彩评论

暂无评论...
验证码 换一张
取 消