2013-11-25 116 views
0

我試圖在單擊前一個列表元素時顯示隱藏的嵌套列表。爲此,我想修改html元素所具有的類。我之前沒有使用過JavaScript/jQuery,所以我對如何嘗試這個有點困惑。用jquery顯示/隱藏html ul

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script> 
<script> 
$('li').click(function() { 
    if ($(this).next('ul').hasClass("hidden")) { 
     $(this).next('ul').removeClass("hidden"); 
     $(this).next('ul').addClass("visible"); 
    } else if ($(this).next('ul').hasClass("visible")) { 
     $(this).next('ul').removeClass("visble"); 
     $(this).next('ul').addClass("hidden"); 
    } 
}); 
</script> 

<ul class="year"> 
    <li>2013</li> 
    <ul class="hidden"> 
     <li>Nov</li> 
     <ul class="hidden"> 
      <li>25</li> 
     </ul> 
    </ul> 
</ul> 
+2

真正的jQuery 1.3 ??? –

+2

您的標記不正確。你不能讓'ul'作爲'ul'的直接子項, – Jashwant

回答

2
<!--Invalid HTML structure fixed, ul should have li elements as its children--> 
<ul class="year"> 
    <li>2013 
     <ul class="hidden"> 
      <li>Nov 
       <ul class="hidden"> 
        <li>25</li> 
       </ul> 
      </li> 
     </ul> 
    </li> 
</ul> 

主要的問題是你不使用dom ready

//dom ready handler 
jQuery(function() { 
    $('li').click(function (e) { 
     //stop propagation else parent li elements click handlers will get triggered 
     e.stopPropagation(); 
     //use toggleClasss 
     $(this).children('ul').toggleClass('hidden visible') 
    }); 
}) 

那麼你可以使用toggleClass切換類

+0

http://jsbin.com/imaTUCUT/1/edit?html,css,js,output working fine fine – oBo

0

嘗試這個

$("id").toggle(); 

應該這樣做。