2017-07-01 55 views
0

我有我的PHP外部文件頭,鏈接到的網頁的HTML元素。 當我點擊它添加活動類,但它不保持活動......我不知道我做錯了什麼! 有人可以幫我嗎? 這是我的代碼:添加class =「活動」使用jQuery

HTML(在php文件):

<ul class="site-header__list"> 
    <li class="site-header__item"> 
     <a class="site-header__link" href="index.php">Home</a> 
    </li> 
    <li class="site-header__item"> 
     <a class="site-header__link" href="portfolio.php">Portfólio</a> 
    </li> 

    <li class="site-header__item"> 
     <a class="site-header__link" href="empresa.php">Empresa</a> 
    </li> 

    <li class="site-header__item"> 
     <a class="site-header__link" href="contactos.php">Contactos</a> 
    </li> 
    </ul> 

JQUERY:

$('.site-header__item a').on('click', function() { 
    $(this).addClass('active'); 
    $(this).sibling().removeClass('active'); 
}); 
+0

沒有兄弟姐妹的方法,它是兄弟姐妹 –

+0

當你點擊一個鏈接,頁面__reloads__ –

+0

....這與php – DelightedD0D

回答

-1
jQuery(document).on("ready page:change", function() { 

    if(window.location.href.indexOf("index.php") > -1){ //or You full URL 

     jQuery('.site-header__item a').addClass('active'); 
     //or other .site-header__item a 
     //ps. better use id not class or add some one more unique class for every button 
     // as this will add class active to all '.site-header__item a' 
    } 

}); 

,是的,這是因爲後( '點擊')事件你頁面重新加載。

+0

無關這可能適用於簡單的需求,但會失敗的任何更復雜 – DelightedD0D

+0

實際上,這根本不會工作 – DelightedD0D

+0

您需要將目標鏈接中的一個,而不是所有鏈接,並一次檢查一個將是一個非常糟糕的設計 – DelightedD0D

-1

下面的代碼將設置適當的活動類當基於請求的URL頁面加載:

<script type="text/javascript"> 
    $(function() { 
    // Set active state on menu element 
    var current_url = window.location.href.split('?')[0]; 
    var full_url = current_url + location.search; 
    var $navLinks = $("ul.site-header__list li a"); 
    // First look for an exact match including the search string 
    var $curentPageLink = $navLinks.filter(
     function() { 
     return $(this).attr('href') === full_url; 
     } 
    ); 
    // If not found, look for the link that starts with the url 
    if (!$curentPageLink.length > 0) { 
     $curentPageLink = $navLinks.filter(
     function() { 
      return $(this).attr('href').startsWith(current_url) || current_url.startsWith($(this).attr('href')); 
     } 
    ); 
    } 
    // If still not found, look for links that contain the page name only 
    if (!$curentPageLink.length > 0) { 
     $curentPageLink = $navLinks.filter(
     function() { 
      return $(this).attr('href').match(current_url) || 
      current_url.match($(this).attr('href')); 
     } 
    ); 
    } 
    $curentPageLink.parents('li').addClass('active'); 
    }); 
</script> 

我們使用這個在我們所有的應用程序和它完美的作品:

enter image description here

+0

謝謝,但這不起作用...當你的意思是你的意思是像:localhost/folder/file.php?或者實際上www.website.com?我沒有那樣的URL,因爲該網站尚未發佈 – Joana

+0

@Joana抱歉,我們使用我們所有的菜單絕對URL,你的也是相對鏈接。我已經更新了上述內容,請參閱https://dodsoftware.com/so/active-menu.html作爲示例 – DelightedD0D