JQuery ul li选择列表

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

  • Item 1
  • Item 2
  • Item 3
  • ...

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

这应该这样做:

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

尝试以下方法:

 $(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元素相关联。 我用它来保存列表的状态。

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

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

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

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