如何添加和删除活动类?

时间:2015-05-14 13:54:18

标签: javascript jquery

当我点击其他锚点时,如何更改类.active-link?

 <div id="settings" class="account-collapse collapse in">
     <div class="account-body">
    <a href="#/PersonalInfo" class="active-link">PERSONAL_INFORMATION</a>
    <a href="#/Notifications">NOTIFICATIONS_SETTINGS</a>
    <a href="#/PasswordChange">CHANGE_PASSWORD</a>
    <a href="#">GAME_SETTINGS</a>
     </div>
     </div>

我尝试了这个,但它不起作用:

    $('div').click(function () {
        var hash = window.location.hash;
        $("a.active-link").removeClass();
        $('a[href="' + hash + '"]').addClass('active-link');


});

2 个答案:

答案 0 :(得分:2)

尝试

$('#settings a').click(function(event) {
   event.preventDefault(); // prevent default action
   $('#settings a').removeClass('active-link'); // remove all active class
   $(this).addClass('active-link'); // apply for current a tag
});

Fiddle

答案 1 :(得分:0)

$('#settings a').not('.active-link').click(function(){//when other links are clicked
    $('#settings .active-link').removeClass('active-link').addClass('mynewclass');
})

DEMO:https://jsfiddle.net/fuk4cyk4/2/