JQuery ul li选择列表

时间:2010-01-15 11:47:23

标签: jquery select html-lists

尝试使用JQuery使用class next和class prev例如滚动列表。

<ul class="selectoption">
    <li> Item 1</li>
    <li> Item 2</li>
    <li> Item 3</li>
    <li> ...   </li>
</ul>
<a href="" class="next">Next</a>
<a href="" class="prev">Back</a>

唯一的问题是我只希望所选的li可见。所以不知何故需要索引李的?非常感谢 - 提前感谢

3 个答案:

答案 0 :(得分: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;
});

答案 1 :(得分:2)

尝试类似:

$(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;
    })    
});

使用jQuery中的数据对象,您可以将任何类型的javascript数据与dom元素相关联。我用它来保存列表的状态。

您可能希望为下一个/上一个步骤中的第一个和最后一个项目添加防护。

答案 2 :(得分:0)

如果您需要索引,请使用以下命令:

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

虽然我会看看Tatu Ulmanen的答案。

相关问题