5

尝试使用 JQuery 滚动使用 class next 和 class prev 例如的 ul li 列表

<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 可见。所以不知何故需要索引li的?非常感谢帮助 - 在此先感谢

4

3 回答 3

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;
});
于 2010-01-15T11:51:39.380 回答
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 元素相关联。我用它来保存列表的状态。

您可能希望在接下来/之前的步骤中为第一个和最后一个项目添加保护。

于 2010-01-15T11:59:01.083 回答
0

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

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

尽管我会改看 Tatu Ulmanen 的答案。

于 2010-01-15T11:53:23.480 回答