jquery添加删除类

发布于 2024-08-21 08:14:15 字数 819 浏览 2 评论 0原文

我有 4 个锚点,我想在单击锚点时向其添加当前类,并同时从其他 3 个锚点中删除该类。这是我的代码。我做错了什么?

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

我的 html 看起来像这样:

<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>

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月寒剑心 2024-08-28 08:14:15

通过使用事件委托,我们只需为所有单击事件绑定一个处理程序。当单击某个锚点(.current 锚点除外)时,我们会剥离其类的 .current 锚点,并使单击的锚点成为新的当前锚点:

$("#thumbs").on("click", "a:not(.current)", function ( event ) {
    $(".current", event.delegateTarget).removeClass("current");
    $(this).addClass("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");
});
吻风 2024-08-28 08:14:15

我想这会对你有帮助

$("a").click(function() {
  $('a').removeClass('current');
  var id = $(this).attr('id');
  $('#'+id).addClass('current');
});

I think this will help you

$("a").click(function() {
  $('a').removeClass('current');
  var id = $(this).attr('id');
  $('#'+id).addClass('current');
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文