当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Active link menu switch weird behavior (Bootstrap)

问题描述:

I am surprised that Bootstrap doesn't provide a tool to automatize switching the .active class between the different links in a .nav bar.

So I searched and got some helped and tried to apply this script to my menu:

$('.nav li a').on('click', function() {

alert("class added " + $(this).parent().find('a').attr('href'));

$(this).parent().parent().find('.active').removeClass('active');

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

});

This is the HTML:

<nav class="navbar navbar-default">

<div class="container-fluid">

<div class="navbar-header">

<!-- blah blah -->

</div>

<div class="collapse navbar-collapse" id="navbar-collapse">

<ul class="nav navbar-nav">

<li class="active"><a href="{{ URL::to('/') }}">Home</a></li>

<li><a href="{{ URL::to('/directions') }}">Directions</a></li>

</ul>

</div>

</div>

</nav>

The weird thing happening is that when I click on Directions the class .active is removed from Home and then goes to Directions, but just for like half a second, and then it goes back to the way it was before.

I "debugged" the targets like this:

$('.nav li a').on('click', function() {

alert("clicked " + $(this).attr('href'));

alert("class removed-> " + $(this).parent().parent().find('.active').find('a').attr('href'));

alert("class added " + $(this).parent().find('a').attr('href'));

$(this).parent().parent().find('.active').removeClass('active');

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

});

And when clicking on Directions the output is:

  1. clicked http://localhost:8000/directions
  2. class removed http://localhost:8000
  3. class added http://localhost:8000/directions

So it seems there's nothing wrong with targeting the correct elements.

What's wrong with the script and why is this weird thing happening?

网友答案:

There must be something else wrong with your code, the code you posted works as expected. Here is a fiddle:

http://jsfiddle.net/StephanWagner/xnVM9/

$('.nav li a').on('click', function() {
    $(this).parent().parent().find('.active').removeClass('active');
    $(this).parent().addClass('active');
});

I removed the collapse classes, so its easier to see in the fiddle, but it also works with the classes.

网友答案:

Since the script didn't work for some reason I ended up doing this for each option in the menu:

<li class="{{ Request::path() == 'directions' ? 'active' : '' }}">
分享给朋友:
您可能感兴趣的文章:
随机阅读: