当我浏览页面时突出显示列表元素

Highlight a list element when I'm browsing the very page

我看到了一些关于这个问题的教程,但其中 none 令我满意。我想突出显示列表中与我正在浏览的页面匹配的单个元素。我用 php 创建了代码,是一个基于 wordpress 的网站,代码确实有效,因为当我回显我所在的 uri 时,它会显示正确的 uri,但是我创建的 if 语句添加了一个 class 当我在网站上时不会输出任何东西..我不明白为什么..无论如何..这是代码:

header.php

<ul class="nav nav-pills sliding" id="Jcollapse">
              <li class="<?php if ($current == "/why-chickapea/"){ echo "current";}?>"><a href="/why-chickapea/"><span>Why Chickapea?</span></a></li>
              <li class="<?php if ($current == "/our-pasta/"){ echo "current";}?>"><a href="/our-story/"><span>Our story</span></a></li>
              <li class="<?php if ($current == "/shop-chickapea/"){ echo "current";}?>"><a href="/shop-chickapea/"><span>Shop</span></a></li>
              <li class="<?php if ($current == "/recipes/"){ echo "current";}?>"><a href="/recipes/"><span>Recipes</span></a></li>
              <li class="<?php if ($current == "/blog/"){ echo "current";}?>"><a href="/blog/"><span>Blog</span></a></li>
            </ul>

我在每个页面中添加了一个 php 片段:

<?php $current = $_SERVER["REQUEST_URI"]; ?>

如果我回显 var $current,我将以这种格式获得正确的 url:/pagename/

最后,我将 class 当前样式设置为黄色

.current {
color:yellow;
}
.current a {
color:yellow;
}

有谁知道我的错误在哪里?

这是页面网站:choosechickapea.com

如您所见,我的代码将生成的 class 是空的,但是如果我回显每个值,我将获得的 uri 就是正确的

最简单的解释是,在设置 $current 之前打印 header。

第二个最简单的解释是作用域不同,这意味着您要么在 non-global 作用域中设置 $current ,要么在 non-global 作用域中读取它,这两者(无论它们是什么)是不同的.由于有人说 wordpress,我想有一些封装到函数中(从而改变了范围)。使用 global 关键字可能是 一个 解决方案,但是一个肮脏的解决方案。但是由于您已经在避免使用 wordpress 函数...

实际代码为:

在 header if 语句中声明之前,先设置变量的值。如果您将在 body 中声明,甚至在使用 a 加载 header 之前声明,例如 require once 或在 wordpress 中:

 <?php get_header(); ?>

这行不通,必须在 header 中设置变量,如下所示:

<?php $current = $_SERVER["REQUEST_URI"]; ?>
    <header class="navbar-fixed-top">

            <ul class="nav nav-pills sliding">
              <li class="<?php if ($current == "/your-url/"){ echo "current";}?>"><a href="/your-url/"><span>your url</span></a></li>
              <li class="<?php if ($current == "/other-url/"){ echo "current";}?>"><a href="/other-url/"><span>/other url/</span></a></li>
              </ul>
</header>