jquery add remove类 [英] jquery add remove class

查看:146
本文介绍了jquery add remove类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个锚点,我想添加一个类的电流锚点,因为它被点击,并从其他3中删除类同时。这是我的代码。我做错了什么?

I have 4 anchors, I want to add a class of current to an anchor as it is clicked and remove the class from the other 3 at the same time. Here's my code. what am I doing wrong?

if ($("ul#thumb a").hasClass("current") {
    $("ul#thumb a").removeClass("current");
    $(this).addClass("current");
});

,我的html看起来像这样:

and my html looks like this:

<ul id="thumbs">
    <li>
        <!-- intro page navi button -->
        <a id="t0" class="active" name="t0">The Company</a>

        <ul class="navi">
            <li><a style="display:none"></a></li>
            <li><a id="t1" name="t1">The Brief</a></li>
            <li><a id="t2" name="t2">The Solution</a></li>
            <li><a id="t3" name="t3">The Result</a></li>
        </ul>

    </li>
</ul>


推荐答案

通过使用事件委托,适用于所有点击事件。当点击一个锚点( .current 锚点除外)时,我们剥离其类的 .current 并使点击的锚点成为新的当前锚点:

By using event-delegation, we only bind one handler for all click events. When an anchor (other than the .current anchor) is clicked, we strip the .current anchor of its class, and make the clicked anchor the new current one:

$("#thumbs").on("click", "a:not(.current)", function ( event ) {
    $(".current", event.delegateTarget).removeClass("current");
    $(this).addClass("current");
});

这篇关于jquery add remove类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆