简体   繁体   English

如何将活动状态类动态更改(添加)到导航链接

[英]How to dynamically change (add) the active state class to a navigation link

Hi I am trying to create a portfolio website. 嗨,我正在尝试创建一个投资组合网站。 In order to not have to recreate the header for each page, I decided do add it using the PHP include function. 为了不必为每个页面重新创建标题,我决定使用PHP include函数添加它。 My only problem now is when I click a link to navigate to another page the active link isn't changing respectively. 我现在唯一的问题是,当我单击链接导航到另一个页面时, 活动链接不会分别更改。
The included HTML 包含的HTML

<ul id="main-menu">
     <li><a href="index.php" class="active">home</a></li>
     <li><a href="about.php">about us</a></li>
     <li><a href="portfolio.php">portfolio</a></li>
     <li><a href="contact.php">contact</a></li>
</ul>

Javascript: 使用Javascript:

 $(document).ready(function(){
    var $menu = $("ul#main-menu li a");                
    $menu.click(function(){
        $menu.each(function(){
            $(this).removeClass("active");
        });
        $(this).addClass("active");                  
    });
 });

I know that the problem is that each time the page loads - it resets the class active to the first link. 我知道问题是每次页面加载时 - 它会将活动的类重置为第一个链接。 What I don't know is: how to dynamically add the active class to the page-matching link? 我不知道的是:如何动态地将活动类添加到页面匹配链接?

You need this: 你需要这个:

  $(document).ready(function(){
        var i = document.location.href.lastIndexOf("/");
        var currentPHP = document.location.href.substr(i+1);
        $("ul#main-menu li a").removeClass('active');
        $("ul#main-menu li a[href^='"+currentPHP+"']").addClass('active');
  });

Try creating a function that runs on page load which selects the hyperlink with the same href as the page. 尝试创建一个在页面加载上运行的函数,该函数选择与页面具有相同href的超链接。

Alternatively, load the main content of the page through AJAX as opposed to the traditional page location change. 或者,通过AJAX加载页面的主要内容,而不是传统的页面位置更改。 JQuery has a good AJAX implementation. JQuery有一个很好的AJAX实现。 Search online for jquery ajax . 在线搜索jquery ajax

Another alternative would be to create a cookie onclick of the hyperlink, and set the selected one by reading the cookie. 另一种方法是在超链接上创建一个cookie,并通过读取cookie来设置所选的cookie。 Although this would be very unreliable (back button, manual url entry, etc). 虽然这将是非常不可靠的(后退按钮,手动URL输入等)。

SIMPLE: 简单:

var link = document.location.href.split('/').slice(-1);   // retrieve page name
$('#main-menu li a.active').removeClass('active');        // remove class 'active'
$('#main-menu li a[href$="'+link+'"]').addClass('active');// and add it to a matching link

jsBin demo jsBin演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM