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
317 views
in Technique[技术] by (71.8m points)

javascript - PHP set active link on page using includes

So I have searched SO for an hour trying to find the answer, and also tried various methods, including this

I am trying to include my pages, along with the navigation. But on the correct page, I need the list-item to have a class of active. The navigation is in header.php and currently looks like this:

<nav>
    <ul>
      <li class="active"> <a href="/">Home</a> </li>
      <li> <a href="#">Apps</a> </li>
      <li> <a href="#">Forums</a> </li>
    </ul>
  </nav>

First, I have no idea if JS(jQuery) would be better, or if PHP was to be better. Both wouldn't matter if it works.

Also I am a bit new with PHP and trying to learn.

What would be the easiest (hopefully) method to use? So I don't have to change a lot of code just to give a nav class="active"

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Asumming you have a $page variable (which contains the name of the page you are currently on):

  <nav>
    <ul>
      <li class="<?php echo ($page == "home" ? "active" : "")?>"> <a href="/">Home</a> </li>
      <li class="<?php echo ($page == "apps" ? "active" : "")?>"> <a href="#">Apps</a> </li>
      <li class="<?php echo ($page == "forums" ? "active" : "")?>"> <a href="#">Forums</a> </li>
    </ul>
  </nav>

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

...