简体   繁体   中英

How do I dynamically insert a CSS class using PHP?

What's wrong with the following code? I would like to dynamically insert "current" CSS class when the respective <li> element is clicked. Thanks!

<?php 
$pg = $_SERVER['PHP_SELF']; 
?>

<section>
    <aside>       
        <nav>
            <ul>
                <li class="<?php if($pg == 'index.php?page=about.php'){echo 'current';} ?>"><a href="index.php?page=about.php">About</a></li>                       
            <li class=""><a href="">Services</a></li> 
            </ul>
        </nav>
    </aside>
<section>

Try with:

<?php 
$pg = $_GET['page'];

$allow = array('about.php', 'main.php', 'other.php');
if ( !in_array($pg, $allow) ) {
    $pg = 'default_value';
}
?>

<section>
    <aside>       
        <nav>
            <ul>
                <li class="<?php if($pg == 'about.php'){echo 'current';} ?>"><a href="index.php?page=about.php">About</a></li>                       
            <li class=""><a href="">Services</a></li> 
            </ul>
        </nav>
    </aside>
<section>
<li class="<?php echo ($_GET['page'] == 'about.php')? 'current' : 'normal'; ?>">
  <a href="index.php?page=about.php">About</a>
</li>

$_SERVER['PHP_SELF'] doesn't return the $_GET vars ( ?page=about.php )

$_SERVER['PHP_SELF'] will start with / and will not include the query string.

You should probably check $_GET['page'] instead.

Well if your looking for clicked at runtime you need javascript not php. Something like this using jQuery will work for you:

$(document).ready(function(){
    $('nav >ul li').click(function(){
        //remove all current classes
        $('.current').removeClass('current');
        $(this).addClass('current');
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM