2011-03-17 51 views
1

我想通过基于现有的开放源代码在网上做我自己的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

我觉得它有助于缩进东西。

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

+1 - 打我吧! – 2011-03-17 20:03:15

+0

好的,请原谅我,如果我得到太具体,但我再次努力学习。我把“alert(current.next()。length);”上面,它一直提醒“1”。我认为这个长度是想告诉我有多少元素匹配选择器?你能告诉我上面多长时间吗? – Stefan 2011-03-17 21:38:40

+0

以及在中心:“next = current.next();”你介意告诉我current.next()在做什么?我又一次认为next()被用来选择下一个元素? – Stefan 2011-03-17 21:42:21

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

我认为在OP中出现了一个错误,使它进入了这段代码。第一个if检查应该是'if($('ul.slideshow li.show')。length)'。 – 2011-03-17 20:04:23

+0

@ChrisShouts:你可能是对的。我会更正,谢谢。 – 2011-03-17 20:05:33