我在HTML页面中有简单的代码:
<?php include("config.php"); ?>
<nav>
<ul>
<li><a href="<?php BASE_URL; ?>/index.php" class="<?php echo $Home; ?>">Home</a></li>
<li><a href="<?php BASE_MEMBERS; ?>/index.php" class="<?php echo $Users; ?>">Users</a></li>
<li><a href="<?php BASE_URL; ?>/contact.php" class="<?php echo $Contact; ?>">Contact</a></li>
</ul>
</nav>
注意:( 在配置文件中)
BASE_URL = <?php define('BASE_URL', 'http://localhost'); ?>
BASE_MEMBERS = <?php define('BASE_MEMBERS', BASE_URL . '/members/'); ?>
现在我需要什么?要将类act-link
添加到活动页面,我有1个解决方案,但子文件夹存在一些问题。我会写一个例子:
注意:配置文件
$addClassActivePage = basename($_SERVER['PHP_SELF']);
$Home = "";
$Users = "";
$Contact = "";
swith($addClassActivePage) {
case "index.php":
$Home = "act-link";
break;
case "members/user.php":
$Users = "act-link";
break;
case "contact.php":
$Contact = "act-link";
break;
}
问题出在子文件夹上。它们在index.php和contact.php页面上显示act-link
,但在用户页面(subfolder / page.php)上不显示。我认为问题出在定义路径或类似符号上。
如果JavaScript以正确的方式解决了此问题,请编写它。谢谢大家
答案 0 :(得分:0)
我将使用JavaScript对其进行重命名:
<?php include("config.php"); ?>
<nav>
<ul>
<li><a href="<?php BASE_URL; ?>/index.php" id="home">Home</a></li>
<li><a href="<?php BASE_MEMBERS; ?>/index.php" id="user">Users</a></li>
<li><a href="<?php BASE_URL; ?>/contact.php" id="contact">Contact</a></li>
</ul>
</nav>
在配置文件中:
$addClassActivePage = basename($_SERVER['PHP_SELF']);
$Home = "";
$Users = "";
$Contact = "";
switch($addClassActivePage) {
case = "index.php":
echo '<script>document.getElementById("home").className = "act-link";</script>';
break;
case = "members/user.php":
echo '<script>document.getElementById("user").className = "act-link";</script>';
break;
case = "contact.php":
echo '<script>document.getElementById("contact").className = "act-link";</script>';
break;
}
因此,您只需要更改几行:
class="<?php echo $Home; ?>"
至id="home"
$Home = "act-link";
至echo '<script>document.getElementById("home").className = "act-link";</script>';
答案 1 :(得分:0)
(PHP 4,PHP 5,PHP 7) basename —返回路径的结尾名称部分
总是
basename($_SERVER['PHP_SELF'])
在最后一个斜杠后返回路径/
删除basename函数,并在switch中的成员大小写之前添加/
basename()
解决问题
配置文件:
$addClassActivePage =$_SERVER['PHP_SELF'];
$Home = "";
$Users = "";
$Contact = "";
switch($addClassActivePage) {
case "index.php":
$Home = "act-link";
break;
case "/members/user.php": // add / before members
$Users = "act-link";
break;
case "contact.php":
$Contact = "act-link";
break;
}