2012-02-14 5 views
0

Мне нужно пройти элементы с превью и следующими кнопками. Вот HTML:jQuery Пред. След. Расширение плагина

<ul> 
     <li><a href="#">Number 1 item</a></li> 
     <li><a href="#">Number 2 item</a></li> 
     <li><a href="#">Number 3 item</a></li> 
     <li><a href="#">Number 4 item</a></li> 
    </ul> 
<input type="button" class="next" value=">" /> 
<input type="button" class="prev" value="<" /> 

JS:

(function(){ 
    var $lis = $('ul li'); 
    var index = 0, lastIndex = 0; 

    start(); // activate first, add event listeners to buttons 

    function next(){ 
     lastIndex = index; 
     if(++index == $lis.length) index = 0; // if next is out of bounds go to first 
     $lis.eq(index).addClass('active'); 
     $lis.eq(lastIndex).removeClass('active'); 
    }; 

    function prev(){ 
     lastIndex = index; 
     if(--index < 0) index = ($lis.length - 1); // if prev is less than first to to last 
     $lis.eq(index).addClass('active'); 
     $lis.eq(lastIndex).removeClass('active'); 
    }; 
    function start(){ 
     $lis.eq(0).addClass('active'); 
     $('.next').click(next); 
     $('.prev').click(prev); 
    } 
})(); 

Этот плагин работает отлично, вот Fiddle

Но я хочу, чтобы расширить его функциональные возможности. Я также хочу активировать эту возможность, нажав на ссылку & запомнить Индекс.

Что я имею в виду: Скажем, я достиг до пункта № 3 при нажатии на следующую кнопку, &, если я просто нажать на
<li><a href="#">Number 1 item</a></li> (пункт №: 1), то я хочу вспомнить свою эту позицию в качестве текущего индекса & Когда я нажимаю на следующую кнопку, я должен перейти к пункту № 2

То же самое также идет с предыдущей кнопкой.

Как расширить эту функциональность?

ответ

1
function li_click(){ 
    lastIndex = index; 
    index = $(this).index(); 
    $lis.eq(index).addClass('active'); 
    $lis.eq(lastIndex).removeClass('active'); 
} 

function start(){ 
    $lis.eq(0).addClass('active'); 
    $('.next').click(next); 
    $('.prev').click(prev); 
    $lis.click(li_click); 
} 

Вот обновленная версия вашего JSFiddle: http://jsfiddle.net/Rtmdj/15/

Также он не выглядит, как вы действительно нуждаетесь в переменной lastIndex, вы можете просто удалить active класс, изменить index, затем добавить active класс к новому index:

$lis.eq(index).removeClass('active'); 
index = $(this).index(); 
$lis.eq(index).addClass('active');