【问题标题】:Add Class in html Dynamically in PHP在 PHP 中动态添加 html 中的类
【发布时间】:2022-04-20 20:06:55
【问题描述】:
我正在尝试使用 Java 脚本或 Jquery 在锚标记中动态添加类。我找到了很多解决方案,但不是我想要的。我想使用 PHP 动态页眉和页脚。为此,我想在我或用户将使用的当前页面中添加“活动”类。
请帮帮我。
提前致谢。
<ul class="nav pull-right">
<li>
<a href="index.php"><i class="icon-home"></i><br />Home</a>
</li>
<li>
<a href="portfolio.html"><i class="icon-camera"></i><br />Portfolio</a>
</li>
</ul>
【问题讨论】:
标签:
javascript
php
jquery
html
【解决方案1】:
<?php
$thisPage = "home";
?>
<html>
<head>
...
...
<body>
<ul class="nav pull-right">
<li <?php if($thisPage == "home") echo 'class="active"'; ?>>
<a href="index.php"><i class="icon-home"></i><br />Home</a>
</li>
<li>
<a href="portfolio.html"><i class="icon-camera"></i><br />Portfolio</a>
</li>
【解决方案2】:
试试看这个
<?php
$urlArr = explode("/", $_SERVER['REQUEST_URI']);
$active_class = array_pop($urlArr); ?>
<ul class="nav pull-right">
<li class="<?php echo ($active_class == "index.php") ? "active" : ""; ?>">
<a href="index.php"><i class="icon-home"></i><br />Home</a>
</li>
<li class="<?php echo ($active_class == "portfolio.html") ? "active" : ""; ?>">
<a href="portfolio.html"><i class="icon-camera"></i><br />Portfolio</a>
</li>
</ul>
【解决方案3】:
如果您希望客户端处理此类事情,跟随 sn-p 应该会让您知道如何去做。你应该注意到你的 index.php 的 URL 应该已经显示在 URL 中了。因为它主要被 htaccess 覆盖。
下面的例子是关于访问http://example.org/portfolio.html的URL
//First, get the current URL
var url = window.location.href; //output: http://example.org/portfolio.html
//Then split them to array by '/'
var arrurl = url.split('/'); //output: Array [ "http:", "", "example.org", "portfolio.html" ]
//Get last portion of the uri
var lasturi = arrurl[arrurl.length-1]; //output: portfolio.html
//Split the last segment by '.'
var arruri = lasturi.split('.'); //output: Array [ "portfolio", "html" ]
//Get the first value of previous array
var page = arruri[0]; //output: portfolio
现在,迭代到导航栏。我给它添加了一个 ID 以获得更好的选择器。 <ul id="mynavbar" class="nav pull-right">
//Iterate to navbar
$('#mynavbar a').each(function () {
//Get attribute href value
var href = $(this).attr("href");
//Split by '.' to array
var arrhref = href.split('.');
//Get the first portion
var hrefportion = arrhref[0];
//Now, we should add class 'active' to the href (also parent li element)
//if the 'hrefportion' is equal to 'page' in this case 'portfolio'
if (hrefportion == page) {
//Add 'active class to the anchor
$(this).addClass("active");
//also its parent li element
var li = $(this).parent();
li.addClass("active");
}
});