2010-10-21 41 views
1

我有一些嵌套的列表和一些jQuery,當單擊父標題時顯示隱藏它們。jQuery切換嵌套列表行爲

IT工作正常,但行爲有點不對。如果嵌套列表可見並且父頭被單擊,我希望隱藏嵌套列表。目前它這樣做,但之後直接顯示嵌套列表。

請參見本的jsfiddle的工作代碼:

http://www.jsfiddle.net/4kG2b/

回答

1

可以觸發檔節目,如果同級<ul>當前是隱藏的(這實際上使得一個切換),像這樣:

$nestList.filter(":hidden").show("fast", function() { 
     $(this).closest("li").removeClass("closed").addClass("open"); 
    }); 

You can test it out here。總之,你可以苗條下來,並得到相同的效果,雖然,這樣的:

$("#expander ul").hide(); 
$("#expander h4").live("click", function() { 
    $(this).siblings("ul").toggle("fast", function(){ 
     $(this).closest("li").toggleClass("open closed"); 
    }).closest("li").siblings(".open").toggleClass("open closed") 
        .children("ul").hide("fast"); 

    $(".scroll").jScrollPane(); 
}); 

You can try that version out here

2

看看這裏: http://www.jsfiddle.net/dactivo/c3vPa/

我們驗證,如果它是可見的,在這種情況下,我們將其隱藏:

if($nestList.is(':visible')) 

這將是代碼:

$("#expander ul").hide(); 
    $("#expander h4").live("click", function(e) { 

     var $this = $(this); 
     var $nestList = $($this).parent().find("ul"); 
     var $scrollPane = $(".scroll"); 

     // hide visible nested lists 
     $("#expander ul:visible").hide("fast", function(){ 
      $(this).closest("li").removeClass("open").addClass("closed"); 
     }); 
     // show this list 
     if($nestList.is(':visible')) 
     { 
      $nestList.hide(); 
     } 
     else 
     { 
     $nestList.show("fast", function() { 
      $(this).closest("li").removeClass("closed").addClass("open"); 
     }); 
     } 
     // resize scrollbars 
     $scrollPane.jScrollPane(); 

     e.preventDefault(); 
    });