在PHP中动态添加html类

gpfsuwkq  于 2022-12-21  发布在  PHP
关注(0)|答案(3)|浏览(186)

我试图通过使用JavaScript或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>
o0lyfsai

o0lyfsai1#

<?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>
woobm2wo

woobm2wo2#

试试这个

<?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>
gopyfrb3

gopyfrb33#

如果你想让客户端来处理这些事情,下面的代码片段应该会给予你如何去做。你应该注意到你的URLindex.php应该已经显示在URL中了。因为它大部分都被htaccess覆盖了。
以下示例介绍如何访问URL http://example.org/portfolio.html

//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");
    }
});

相关问题