一段时间以来,我一直在使用下面的代码动态地编写html页面标题,并向菜单项添加一个活动类。这仍然是实现这一目标的一个很好的原因吗?还是有更好/更聪明/最佳的方法来实现同样的目标?

<?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='contact.php'? 'class="active"' : '');?>

菜单示例
<ul id="nav">
<li><a href="index.php"  target="_parent" <?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='index.php'? 'class="active"' : '');?>><span>Home</span></a></li>
<li><a href="services.php"  target="_parent" <?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='services.php'? 'class="active"' : '');?><?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='services-landlords.php'? 'class="active"' : '');?><?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='services-sellers.php'? 'class="active"' : '');?><?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='services-tennants.php'? 'class="active"' : '');?>><span>Our Services</span></a></li>
<li><a href="for-sale.php" target="_parent" <?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='sales.php'? 'class="active"' : '');?>><span>Sales</span></a></li>
<li><a href="to-let.php" target="_parent" <?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='lettings.php'? 'class="active"' : '');?>><span>Lettings</span></a></li>
<li><a href="register.php"  target="_parent" <?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='register.php'? 'class="active"' : '');?><?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='register-thanks.php'? 'class="active"' : '');?>><span>Register</span></a></li>
<li><a href="contact.php"  target="_parent" <?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='contact.php'? 'class="active"' : '');?>><span>Contact Us</span></a></li>
</ul>

页面标题示例
<?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='services.php'? 'Services' : '');?>
<?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='services-landlords.php'? 'Services for Landlords' : '');?>

最佳答案

你可以把它放到函数里。

function menuIsActive ($filename)
{
    echo (basename($_SERVER['SCRIPT_FILENAME']) == $filename)
    {
        echo ' class="active" ';
    }
}

前任。
<li><a href="contact.php" target="_parent" <?php menuIsActive("contact.php"); ?>>Contact Us</a></li>

10-08 12:40