簡體   English   中英

JQuery ul li選擇列表

[英]JQuery ul li select list

嘗試使用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可見。 所以不知何故需要索引李的? 非常感謝 - 提前感謝

這應該這樣做:

// 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的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM