如何使用php include文件向元素添加活动类


How to add active class to an element using php include file

我有一个侧边栏的sidebar-right.html文件,它有以下元素:

<div class="col-sm-2">
  <div class="list-group">
     <a href="Sub-Investment.php" class="list-group-item">New investment plan</a>
     <a href="open-creditcard.php?action=credit" class="list-group-item">Apply credit card</a>
     <a href="open-creditcard.php?action=limit" class="list-group-item">Increase credit limit</a>
  </div>
</div>
</div>
</div>
</div>

我在另一个名为open-creditcard.php的文件中调用此页面使用include "..'View''sidebar-right.html";

所以我这个页面的最终URL将是这样的:
http://localhost/obis/Controller/open-creditcard.php?action=limithttp://localhost/obis/Controller/open-creditcard.php?action=credit

我想添加一个类active的列表组在sidebar-right.html动态使用php。

我试过这样做:
<a href="open-creditcard.php?action=credit" class="list-group-item" <?php if($_SERVER['PHP_SELF'] == "/open-creditcard.php?action=credit") echo 'class="list-group-item active"'; ?>>Apply credit card</a>
但这行不通。有什么我想念的吗?有人能帮帮我吗?

$_SERVER['PHP_SELF']不包含查询字符串,但您可以使用$_GET['action']代替:

<a href="open-creditcard.php?action=credit" class="list-group-item<?= isset($_GET['action']) && $_GET['action'] == 'credit' ? ' active' : '' ?>">Apply credit card</a>
<a href="open-creditcard.php?action=limit" class="list-group-item<?= isset($_GET['action']) && $_GET['action'] == 'limit' ? ' active' : '' ?>">Increase credit limit</a>
<a href="open-creditcard.php?action=credit" class="list-group-item<?= isset($_GET['action']) && $_GET['action'] == 'credit' ? ' active' : '' ?>">Apply credit card</a>
<a href="open-creditcard.php?action=limit" class="list-group-item<?= isset($_GET['action']) && $_GET['action'] == 'limit' ? ' active' : '' ?>">Increase credit limit</a>