开发者

What is a more readable version of this slideshow code?

I am trying to learn by making my own jQuery slideshow based on existing open source code on the net.

I am getting lost in one chunk of coding and I think it's mainly because I am not very strong to begin with in programming/jQuery, and also the guy who wrote it used a bunch of ternary operators (I believe that's what this is).

Could someone please help me break this down and maybe even replace the ternary operators with more "traditional" operators?

//if no IMGs have the show class, grab the first image
var current = ($('ul.slideshow li.show') ?  $('ul.slideshow li.show') : $('#ul.slideshow li:first'));

//Get next image, if it reached the end of the slideshow, rotate it back to the first image
var next = ((current.next().length) ? ((current.next().attr('id') == 'slideshow-caption') ? $('ul.slideshow li:first') :current.next()) : $('ul.slideshow li:first'));

I am mostly confused on th开发者_如何学Goe last line.


I find it helps to indent things.

var next = (
  (current.next().length) ? (
    (current.next().attr('id') == 'slideshow-caption') ?
      $('ul.slideshow li:first')
      : current.next()
    )
    : $('ul.slideshow li:first')
  );

Which would be the equivalent of:

var next;
if (current.next().length) {
  if (current.next().attr('id') == 'slideshow-caption') {
    next = $('ul.slideshow li:first');
  } else {
    next = current.next();
  }
} else {
  next = $('ul.slideshow li:first');
}


//if no IMGs have the show class, grab the first image
var current;
if ($('ul.slideshow li.show').length){
  // if we found an item with the show class, assign it to current
  current = $('ul.slideshow li.show')
}else{
  // otherwise nothing is being shown, default to first element
  $('#ul.slideshow li:first');
}

//Get next image, if it reached the end of the slideshow, rotate it back to the first image
var next;
// if there are additional elements (true when .length > 0)
if (current.next().length){ 
  // is the next element the slideshow caption
  if (current.next().attr('id') == 'slideshow-caption') 
    // it is, so go back to the first element
    next = $('ul.slideshow li:first')
  // it's not, continue on with the next element
  else
    next = current.next();
}else{
  // there is no next element, go back to first.
  next = $('ul.slideshow li:first');
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜