Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

javascript - how to set active class to nav menu from twitter bootstrap

I'm new to the twitter bootstrap. Using there navigation menus . I'm trying to set active class to selected menu. my menu is -

<div class="nav-collapse">
  <ul class="nav">
    <li id="home" class="active"><a href="~/Home/Index">Home</a></li>
    <li><a href="#">Project</a></li>
    <li><a href="#">Customer</a></li>
    <li><a href="#">Staff</a></li>
    <li  id="broker"><a href="~/Home/Broker">Broker</a></li>
    <li><a href="#">Sale</a></li>
  </ul>
</div>

I tried following thing after googling on this that i have to set active class on each page from menu like as--

<script>
  $(document).ready(function () {
    $('#home').addClass('active');
  });
</script>

but problem for above is that i set home menu selected by default. Then it always get selected. Is there any other way to do this ? , or which i can generalize and keep my js in layout file itself?

After executing application my menu looks - enter image description here

after clicking on other menu item i get following result- enter image description here

And i added following scripts on Index view and Broker view ---

<script>
  $(document).ready(function () {
    $('#home').addClass('active');
  });
</script>

<script>
  $(document).ready(function () {
    $('#broker').addClass('active');
  });
</script>

respectively.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use this JavaScriptjQuery code:

// Sets active link in Bootstrap menu
// Add this code in a central place usedshared by all pages
// like your _Layout.cshtml in ASP.NET MVC for example
$('a[href="' + this.location.pathname + '"]').parents('li,ul').addClass('active');

It'll set the <a>'s parent <li> and the <li>'s parent <ul> as active.

A simple solution that works!


Original source:

Bootstrap add active class to li


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...