使用href ID触发jQuery .toggleClass()

时间:2013-11-01 01:59:41

标签: jquery toggleclass

以下代码是切换(插入和删除)类" menu-min"对于菜单中单击的每个链接。我希望这个脚本只在单击ID为#toggle-pane的链接时才这样做。我不知道该怎么做。任何帮助表示赞赏。

<ul class="cbp-vimenu">
        <li><a href="#" class="icon-logo">&nbsp;</a></li>
        <li>
            <a href="#" class="icon-archive"><span class="menu-text"> Dashboard </span></a>
        </li>
        <li>
            <a href="#" class="icon-search"><span class="menu-text"> Search </span></a>
        </li>
        <li>
            <a href="#" class="icon-location"><span class="menu-text"> Location </span></a>
        </li>
        <li>
            <a href="#" class="icon-images"><span class="menu-text"> Images </span></a>
        </li>
        <li>
            <a href="#" class="icon-download"><span class="menu-text"> Download </span></a>
        </li>
        <li>
            <a id="toggle-pane" href="#" class="icon-pencil"><span class="menu-text"> Add Class </span></a>
        </li>
        <!-- Example for active item:
        <li class="cbp-vicurrent"><a href="#" class="icon-pencil">Pencil</a></li>
        -->
    </ul>`

这是我的jQuery

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
    $( ".cbp-vimenu" ).click(function() {
        $( this ).toggleClass( "menu-min" );
    });
</script>

2 个答案:

答案 0 :(得分:2)

仅将点击事件注册到#toggle-pane元素,然后在里面找到cbp-vimenu元素并切换其类

$("#toggle-pane").click(function () {
    $('.cbp-vimenu').toggleClass("menu-min");
    //or $(this).closest('.cbp-vimenu').toggleClass("menu-min");
    //I don't think you want to use closest since it doesn't look like you have many elements with class cbp-vimenu
});

答案 1 :(得分:0)

$("#toggle-pane").click(function () {
    $(this).closest('ul.cbp-vimenu').toggleClass("menu-min");
});

参考文献

.closest()

id selector