使用 jQuery-twitter bootsrap 按钮添加/删除类以锚定标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19142653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:17:36  来源:igfitidea点击:

Adding/removing class to anchor tag with jQuery- twitter bootsrap buttons?

jqueryhtmlcsstwitter-bootstrapanchor

提问by Landon Dorrier

I have a single page site. My navigation consists of a few buttons styled by bootstrap 3.

我有一个单页网站。我的导航由几个由 bootstrap 3 设计的按钮组成。

Since it is a single page, the buttons are anchor tags. I want to be able to have an .activeclass applied to the last anchor tag that has been clicked.

由于它是单个页面,因此按钮是锚标记。我希望能够将一个.active类应用于已单击的最后一个锚标记。

This is my HTML:

这是我的 HTML:

<a href="#home">
    <button type="button" class="btn btn-default btn-lg active">
    <span class="glyphicon glyphicon-home"></span> Home
    </button>
</a>

<a href="#about">
    <button type="button" class="btn btn-default btn-lg">
    <span class="glyphicon glyphicon-user"></span> About
    </button>
</a>

And my CSS:

还有我的 CSS:

.btn-default:hover,
.btn-default:focus,
.btn-default:active,
.btn-default.active,
.open .dropdown-toggle.btn-default {
border:none;
background-color: #2C3E50;
border-bottom: 1px solid #2C3E50;
}

回答by Reinstate Monica Cellio

Try this...

尝试这个...

$(function() {
    $("a").on("click", function() {
        $(".btn-default.active").removeClass("active");
        $(this).find(".btn-default").addClass("active");
    });
});

or...

或者...

$(function() {
    $("a").on("click", function() {
        $("a.active").removeClass("active");
        $(this).addClass("active");
    });
});

Not sure if the active class should be added to the link or the enclosed button, so there's 1 for each.

不确定是否应将活动类添加到链接或封闭按钮中,因此每个类都有 1 个。

回答by Darren

You could use jQuery addClass

你可以用 jQuery addClass

$('a#buttonid').click(function(){
    $(this).addClass('active');
});

You'd check to make sure it doesn't already have that class and remove the active class from the other buttons aswell.

您会检查以确保它没有该类,并从其他按钮中删除活动类。