【问题标题】:Jquery: only show the UL with a child LI set to class = activeJquery:仅显示带有子 LI 设置为 class = active 的 UL
【发布时间】:2013-04-29 20:32:56
【问题描述】:

我有这样的菜单结构:

<ul id="accordion">
 <li><a href="#">Books</a>
  <ul>
    <li><a href="thrillers.html">Thrillers</a></li>
    <li><a href="scifi.html">Sci-fi</a></li>
    <li><a href="nf.html">Non-fiction</a></li>
  </ul>
 </li>
 <li><a href="#">Games</a>
  <ul>
    <li><a href="rpg.html">RPG</a></li>
    <li><a href="sim.html">Simulations</a></li>
    <li><a href="action.html">Action</a></li>
  </ul>
 </li>
</ul>

(等等)

现在,我们点击“RPG”我希望在 RPG 页面上打开游戏子菜单。所以,我决定在选择的 LI 中添加一个类:

...
<ul>
  <li class="active"><a href="rpg.html">RPG</a></li>
  <li><a href="sim.html">Simulations</a></li>
  <li><a href="action.html">Action</a></li>
</ul>
...

现在,我想做的是让 jQuery 找到 class="active" 的 UL,然后打开该 UL。

我只是这个 jQuery:

<script>

$(document).ready(function () {

    //hide all submenu's onLoad
    $('#accordion li').children('ul').slideUp('fast');  

    $('#accordion a.item').click(function () {

        /* FIRST SECTION */

        //slideup or hide all the Submenu
        $('#accordion li').children('ul').slideUp('fast');  

        //remove all the "Over" class, so that the arrow reset to default
        $('#accordion a.item').each(function () {
            if ($(this).attr('rel')!='') {
                $(this).removeClass($(this).attr('rel') + 'Over');  
            }
        });

        /* SECOND SECTION */        

        //show the selected submenu
        $(this).siblings('ul').slideDown('fast');

        //add "Over" class, so that the arrow pointing down
        $(this).addClass($(this).attr('rel') + 'Over');         

        return false;

    });

});

</script>

在 onLoad 部分之后我需要什么才能只有我想要打开的那个?

【问题讨论】:

    标签: jquery html-lists accordion submenu


    【解决方案1】:

    这可能会有所帮助:

    $('#accordion > li > ul > li.active').parent().slideDown('fast');
    

    【讨论】:

    • 太棒了,谢谢。看起来很简单,但我没有使用 > 字符。所以,这就是我没有成功的原因。再次感谢。
    【解决方案2】:

    尝试获取直子&gt;active li:

    $(document).ready(function () {
        $('#accordion li').children('ul').slideUp('fast'); //<--hide all child uls
        $('#accordion > li').click(function () { ///<---perform a click event on li
            $(this).addClass('active').siblings('li').removeClass('active'); //<--add active class to the clicked element and remove from other siblings li
            $(this).siblings('li').find('ul').slideUp('fast'); // <---find the ul in the siblings and slide those up
            $('> ul', this).slideDown('fast'); // <--then perform the slideDown
        });
    });
    

    FIDDLE DEMO你可以试试这个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多