PHP使用包含在页面上设置活动链接

2022-01-10 00:00:00 include jquery navigation php javascript

所以我搜索了一个小时试图找到答案,还尝试了各种方法,包括这个

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

我正在尝试包含我的页面以及导航.但是在正确的页面上,我需要列表项有一个 active 类.导航在 header.php 中,目前看起来像这样:

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>

首先,我不知道 JS(jQuery) 是否会更好,或者 PHP 是否会更好.如果它有效,两者都无关紧要.

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.

另外,我对 PHP 有点陌生,正在努力学习.

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

最简单(希望)使用的方法是什么?所以我不必为了提供导航而更改很多代码 class="active"

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"

推荐答案

假设您有一个 $page 变量(其中包含您当前所在页面的名称):

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>

相关文章