0

以下代码为在菜单中单击的每个链接切换(插入和删除)类“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>
4

2 回答 2

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
});
于 2013-11-01T02:01:37.920 回答
0
$("#toggle-pane").click(function () {
    $(this).closest('ul.cbp-vimenu').toggleClass("menu-min");
});

参考

.closest()

id 选择器

于 2013-11-01T02:02:49.560 回答