jquery add remove class

2019-01-23 05:08发布

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");
});

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>

标签: jquery class add
2条回答
欢心
2楼-- · 2019-01-23 05:17

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");
});
查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-23 05:22

I think this will help you

$("a").click(function() {
  $('a').removeClass('current');
  var id = $(this).attr('id');
  $('#'+id).addClass('current');
});
查看更多
登录 后发表回答