JQuery ul li select list

2019-06-22 16:11发布

问题:

Trying to use JQuery to scroll through a ul li list using class next and class prev e.g.

<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>

Only thing is I only want the selected li to be visible. So somehow need to index the li's? Help much appreciated - thanks in advance

回答1:

This should do it:

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


回答2:

Try something like:

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

With the data object in jQuery, you can associate any kind of javascript data with a dom element. I have used this to save the state of the list.

You might want to add guards for the first and last item in the next / previous steps.



回答3:

If you want your index, use the following:

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

Although I would look at Tatu Ulmanen's answer instead.