2010-01-15 6 views
5

JQuery를 사용하여 클래스 next와 클래스 prev를 사용하여 ul li 목록을 스크롤하려고합니다.JQuery ul li 목록 선택

내가 선택한 li 만 보일뿐입니다. 어떻게 든 리의 색인을 생성해야합니까? 많이 감사 도움말 - 미리 감사

답변

9

에서이 그것을 수행해야합니다

// Hide all but the first 
$('.selectoption li').not(':first').hide(); 

// Handle the click of prev and next links 
$('.prev, .next').click(function() { 
    // Determine the direction, -1 is prev, 1 is next 
    var dir = $(this).hasClass('prev') ? -1 : 1; 
    // Get the li that is currently visible 
    var current = $('.selectoption li:visible'); 

    // Get the element that should be shown next according to direction 
    var new_el = dir < 0 ? current.prev('li') : current.next('li'); 

    // If we've reached the end, select first/last depending on direction 
    if(new_el.size() == 0) { 
     new_el = $('.selectoption li:'+(dir < 0 ? 'last' : 'first')); 
    } 

    // Hide them all.. 
    $('.selectoption li').hide(); 
    // And show the new one 
    new_el.show(); 

    // Prevent the link from actually redirecting the browser somewhere 
    return false; 
}); 
+0

안녕하세요 Tatu Ulmanen, 약간의 변경으로이 기능을 사용해 주셔서 감사합니다. if (next.size() == 0) {next = dir == 'prev'? $ ('. 선택 옵션 li : 첫 번째') : $ ('. 선택 옵션 li : 첫 번째'); } - 이전 버튼이 nil 항목을 만들지 못하도록합니다. – russell

+0

@russell, 작동해야하지만, 그렇지 않은 경우 수정하면'if (next.size() == 0) {next = $ ('. selectoption li : first'); }', 내부 조건부에 대한 필요가 없습니다. 그러나 그것이 당신을 위해 일한 것이 좋다면, 받아 들여진 답을 표시하는 것을 잊지 마십시오 :) –

0

을 당신이 당신의 인덱스를 원하는 경우, 다음을 사용 :

$("#selectoption>li").click(function(){ 
    alert($(this).index()); 
}); 

을 내가 대신 타투 Ulmanen의 대답에 보일 것이다 있지만.

2

같은 시도 : jQuery를에있는 데이터 객체와

$(function(){ 
    // initialization 
    $(".selectoption").data("index",1).find("li:not(:first)").hide(); 

    // previous 
    $(".previous").click(function(){ 
     $(".selectoption").data(
      "index", 
      $(".selectoption").data("index") - 1 
    ); 
     $(".selectoption li").hide().eq($(".selectoption").data("index")).show(); 
     return false; 
    }); 

    // next 
    $(".next").click(function(){ 
     $(".selectoption").data(
      "index", 
      $(".selectoption").data("index") + 1 
    ); 
     $(".selectoption li").hide().eq($(".selectoption").data("index")).show(); 
     return false; 
    })  
}); 

을, 당신은 DOM 요소와 자바 스크립트 모든 종류의 데이터를 연결할 수 있습니다. 나는 이것을 사용하여 목록의 상태를 저장했다.

다음/이전 단계의 첫 번째 항목과 마지막 항목에 대해 보호를 추가 할 수 있습니다.