2017-08-16 65 views
1

我有一个从一个页面导航到另一个链接的列表。所选链接会短暂变色(变为红色),然后返回默认颜色。我已经阅读了很多关于这个问题的消息,但是我的解决方案都没有工作。jQuery选择的链接文字颜色不会永久改变

php文件:

<div class="navBar"> 
     <a href="index.php">Home</a>  <a href="about.php">About</a>  <a href="galleries.php">Gallery</a>  <a href="equipment.php">Equipment</a>  <a href="links.php">Links</a>  <a href="contact.php">Contact</a> 
    </div> 

    <script> 
     $(document).ready(function() 
      { 
       alert('in navBar'); 
       /*$('.aNavBar').click(function(event) 
        { 

        };*/ 

       $('.navBar a').click(function() 
        { 
         alert("in click function"); 
         $('.navBar a.selected').removeClass('selected'); 
         $(this).addClass('selected'); 
         $('.navBar a.lastclicked').removeClass('lastclicked'); 
         $(this).addClass('lastclicked'); 
        }); 
      }); 
    </script> 

css文件:

.navBar 
{ 
    background: white; 
    border: 0; 
    font-size: 20px; 
    height: 10%; 
    margin: 0; 
    padding: 0; 
    text-align: center; 
    white-space: pre; 
    width: 100%; 
} 

.navBar.selected 
{ 
    color: red; 
} 

.navBar a.lastclicked 
{ 
    color: red; 
} 

.navBar a.selected 
{ 
    color: red; 
} 

正如你所看到的,我已经尝试使用 '选择' 和 'lastclicked'。

+0

你的代码没有意义,你将删除选定的和lastclicked的类,并再次添加相同的类。你想添加选定和lastclicked的类到具有navbar类的父div? –

+1

单击链接时,浏览器导航到新页面,这些元素与接收红色类别的元素不同。 – Jasen

回答

1

添加/删除类将无关紧要,因为当用户在页面之间导航时,add/remove类会丢失。

的选择是决定从URL被查看使用正则表达式,如页面:

var href = 'http://www.example.com/test/pagename/'; 
//href = location.href; 
var page = href.match(/^.*?\/([^\/]*)\/*$/)[1]; 
// This will give you 'pagename' 

href = 'http://www.example.com/test/index.php'; 
page = href.match(/^.*?\/([^\/]*)\/*$/)[1]; 
// This will give you index.php 

从那里,你可以这样做:

$.each($('.navBar a'), function(i,e){ 
    if($(e).attr('href') === page){ 
     $(e).addClass('selected'); 
    } 
    }) 

要确定是否页被查看匹配任何hrefs,如果是,添加选定的类。

这不是没有缺点,但:

  • 如果正在htaccess例如删除文件扩展名,该URL会说index而HREF会说index.php,为此不匹配。
  • 如果URL是像http://www.example.com/这将返回www.example.com

有需要做来解决这样的事情额外的工作。

虽然希望它有帮助!

Here is a jsFiddle显示在行动中的概念。