更改<a> class place when change page

时间:2015-04-28 23:07:38

标签: html html5 nav

How can I include that class="selected" in different pages?

my code:

                    <li><a href="index.html" class="selected">Home</a></li>                             
                    <li><a href="register.html">Register</a></li>                                                                       
                    <li><a href="faq.html">FAQ</a></li>

so after I want to go in other pages to do something like that

                    <li><a href="index.html" >Home</a></li>                             
                    <li><a  href="register.html" class="selected">Register</a></li>                                                                     
                    <li><a  href="faq.html" >FAQ</a></li>

PS: I use header.php, to manage pages

in all pages use:

// include header
require_once(SITE_TEMPLATES_PATH . '/partial/_header.inc.php');

anyone can tell me how can I do that?

2 个答案:

答案 0 :(得分:1)

你可以使用一个简单的jquery代码,首先不要忘记将它添加到你的head标签:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>

然后你可以使用这个脚本:

$(document).ready(function() {
var path = window.location.pathname;
var page = path.split("/").pop();
//nav is the nav tag if you are putting your links in a nav if not you can use a selector of class or id
$("nav a").each(function(){
var x=$(this).attr("href");
if((x.indexOf(page)!=-1)&&(page!="")){
$(this).parent().addClass("selected");
}
}); 
});

答案 1 :(得分:1)

你可以使用PHP这样做:

<?php $page = basename($_SERVER['SCRIPT_NAME']); ?>

<li><a href="index.html" <?php if ($page=='index.html') 
      echo ' class="selected"'; ?>>Home</a></li>                             
<li><a  href="register.html" <?php if ($page=='register.html') 
      echo ' class="selected"'; ?>>Register</a></li>                                                                     
<li><a  href="faq.html" <?php if ($page=='faq.html') 
      echo ' class="selected"'; ?>>FAQ</a></li>