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

流过昼夜 提交于 2019-12-12 05:04:51

问题


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

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

This is my 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:

.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;
}

回答1:


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.




回答2:


You could use 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.



来源:https://stackoverflow.com/questions/19142653/adding-removing-class-to-anchor-tag-with-jquery-twitter-bootsrap-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!