how to add active to a tag and li tag with php

后端 未结 5 1418
情深已故
情深已故 2021-01-24 01:45

Trying to get my PHP navigation bar to work. I am trying to echo the page where the user is on with the attached class of active if the page is current.

Here is my code

相关标签:
5条回答
  • 2021-01-24 02:05

    Do like this :

    $pages = array(
        "index.php" => "Home", 
        "pages/contact.php" => "Contact Us", 
        "pages/services.php" => "services", 
        "pages/employees.php" => "Employees", 
        "pages/dashboard.php" => "Dashboard");
    
    foreach ($pages as $url => $label) {
      echo '<li ';
    
      if(basename($_SERVER['REQUEST_URI'])== basename($url)){   // this line
            echo "class='active'";                              // this line
       }                                                        // and this line
      echo '><a href=', "$url", '>', "$label", '</a></li>';
    }
    ?>
    
    0 讨论(0)
  • 2021-01-24 02:09
    <?php 
    
    if ($_SERVER['REQUEST_URI'] === "/page") echo 'id="active"'; 
    
    ?>
    
    0 讨论(0)
  • 2021-01-24 02:22
    <?php
    $pages = array(
        "index.php" => "Home", 
        "pages/contact.php" => "Contact Us", 
        "pages/services.php" => "services", 
        "pages/employees.php" => "Employees", 
        "pages/dashboard.php" => "Dashboard");
    
    $cururl = $_SERVER['PHP_SELF'];
    
    foreach ($pages as $url => $label) {
      echo '<li';
    
      if (strpos($cururl,$url)!==false) {
        echo ' class="active"';
      }
      echo '><a href=', "$url", '>', "$label", '</a></li>';
    }
    ?>
    

    This should work for you. Because, you were trying to access the url address using GET-METHOD. Here, I have fetched your url by doing $cururl = $_SERVER['PHP_SELF']; and checked for the active menu item as if (strpos($cururl,$url)!==false)

    0 讨论(0)
  • 2021-01-24 02:26

    Try this:

    echo 'class="active"';
    
    0 讨论(0)
  • 2021-01-24 02:28

    Not tested:

    <?php
    $pages = array(
        "index.php" => "Home", 
        "contact.php" => "Contact Us", 
        "services.php" => "services", 
        "employees.php" => "Employees", 
        "dashboard.php" => "Dashboard");
    
    $uri = explode("/", stripslashes($_SERVER['REQUEST_URI']));
    
    foreach ($pages as $url => $label) {
      echo '<li ';
      echo in_array($url, $uri)?'class="active"':'';
      echo '><a href="'.$url.'">'.$label.'</a></li>';
    }
    ?>
    

    Note: it is a best practice to put your other page files in the root next to yout index.php

    0 讨论(0)
提交回复
热议问题