JQuery ul li 选择列表

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进行索引?非常感谢您的帮助 - 预先感谢。

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

嗨,Tatu Ulmanen,感谢您的工作,稍作修改后它可以正常运行 - 如果(next.size() == 0) { next = dir == 'prev' ? $('.selectoption li:first') : $('.selectoption li:first'); } - 防止了“上一个”按钮创建空条目。 - russell
@russell,这个应该可以运行,但如果不行,你的修改可以简化为if(next.size() == 0) { next = $('.selectoption li:first'); },不需要内部条件判断。但是如果它对你有用,请标记答案为已接受 :) - Tatu Ulmanen

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元素关联起来。我已经使用它来保存列表的状态。
在下一步/上一步中,您可能希望为第一个和最后一个项目添加保护。

0
如果您想要索引,请使用以下内容:
$("#selectoption>li").click(function(){
    alert($(this).index());
});

虽然我建议您看一下Tatu Ulmanen的答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接