这个幻灯片代码的更具可读性的版本是什么?

时间:2011-03-17 19:55:55

标签: jquery

我正在尝试通过基于网络上现有的开源代码制作我自己的jQuery幻灯片来学习。

我迷失在一段编码中,我认为这主要是因为我在编程/ jQuery中不是很强大,而且编写它的人使用了一堆三元运算符(我相信这就是这个是)。

有人可以帮我解决这个问题,甚至可能用更“传统”的运营商取代三元运营商吗?

//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'));

我最后一行感到困惑。

2 个答案:

答案 0 :(得分:2)

我觉得缩进是有帮助的。

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

这相当于:

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');
}

答案 1 :(得分:1)

//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');
}