如何为导航栏添加活动类?

时间:2019-09-26 17:28:21

标签: jquery html css

我一直在努力为导航栏选择添加“活动”类,但我似乎无法正确地做到这一点。我通过遵循一个示例在这里使用jQuery来添加类,但是我很难实现这一点。所以当我按下链接按钮例如回到首页应该激活添加活动类。事实是没有,找不到控制台错误。它只是不会将活动类添加到导航栏链接。

这就是我所做的。

我的导航栏html

<nav class="navbar navbar-expand-md navbar-light bg-light sticky">
        <a href="#" class="navbar-brand">
            <img src="Assets/Images/spicy-food.svg" height="28" alt="SpiceFoods">
        </a>
        <h2 class="Nav-brand">Spice Foods</h2>
        <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarCollapse">
            <div class="navbar-nav ml-auto">
                <a href="#" data-value="carouselIndicator" class="nav-item nav-link btn-ripple">Home</a>
                <a href="#" data-value="About" class="nav-item nav-link btn-ripple">About</a>
                <a href="#" data-value="Products" class="nav-item nav-link btn-ripple">Our Spices</a>
                <a href="#" data-value="Contact" class="nav-item nav-link btn-ripple">Contact Us</a>
            </div>
        </div>
    </nav>

这是CSS

.navbar-nav div>a.active {
    background-color: rgba(0, 0, 0, 0.22);
    font-weight: 600;
}

这是我的jQuery

$('.navbar-nav a').on('click', function () {
        console.log("Click");
        $('.navbar-nav').find('a.active').removeClass('active');
        $(this).parent('a').addClass('active');
    });

我如何实现这一目标。帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您只需要更改一行即可。

替换此行

$(this).parent('a').addClass('active');

使用

$(this).addClass('active');

答案 1 :(得分:2)

请参阅以下评论,以了解已更改的内容:

create table itinerary_detail (
  tour_no number(6),
  version_no number(6),
  itinerary_detail_no number(6)
);

insert into itinerary_detail (tour_no, version_no, itinerary_detail_no) values (1, 10, 5);
insert into itinerary_detail (tour_no, version_no, itinerary_detail_no) values (1, 10, 5);
insert into itinerary_detail (tour_no, version_no, itinerary_detail_no) values (1, 17, 5);
insert into itinerary_detail (tour_no, version_no, itinerary_detail_no) values (1, 17, 5);
insert into itinerary_detail (tour_no, version_no, itinerary_detail_no) values (1, 17, 5);
insert into itinerary_detail (tour_no, version_no, itinerary_detail_no) values (2, 10, 5);
insert into itinerary_detail (tour_no, version_no, itinerary_detail_no) values (3, 10, 5);
$('.navbar-nav a').on('click', function() {
  $('.navbar-nav').find('a.active').removeClass('active');
  // you had  $(this).parent('a').addClass('active') - but there IS no "a" parent... you want the active class on the clicked element....
  $(this).addClass('active');
});
/* you had .navbar-nav div > a.active ... however, there's no div between the navbar and the a.... */
.navbar-nav .active {
  background-color: rgba(0, 0, 0, 0.22);
  font-weight: 600;
}