使用php代码导航时,Jquery'主动'类

时间:2015-04-16 13:31:08

标签: php jquery

所以,我建立一个网站,我想给一个"活跃"根据用户访问的页面,我的菜单类。我是Jquery的新手,所以我不知道这是否是最好的方法,或者是否有更好的代码来实现我想要的。

目前我的主要结构是:

  • 标题
  • Navbar where is the menu i'm giving the active class
  • 内容called with the php code
  • 页脚

加载另一个页面时我唯一需要改变的是,content如果它是php或ajax,它并不重要。实际上,我知道ajax可以做得更有活力,但我还不知道该怎么做。

所以这是我为我的li a元素提供活动课程的代码:

php加载页面:

<?php
    if(!empty($_GET['p'])){
        if (file_exists ($_GET['p'].".php")){
            include($_GET['p'].".php");
        } else include ("erro.php");
    } else include("content/home.php");
?>

Jquery给它一个类:

$(document).ready(function() {
    var home = $('a[href$="home"]'),
        servicos = $('a[href$="servicos"]'),
        advogados = $('a[href$="advogados"]'),
        escritorio = $('a[href$="escritorio"]'),
        noticias = $('a[href$="noticias"]'),
        contato = $('a[href$="contato"]');
    $(function() {
        var loc = window.location.href;
        if(/home/.test(loc)) {
            $('.navbar li').find(home).addClass('active');
        } else if(/servicos/.test(loc)) {
            $('.navbar li').find(servicos).addClass('active');
        } else if(/advogados/.test(loc)) {
            $('.navbar li').find(advogados).addClass('active');
        } else if(/escritorio/.test(loc)) {
            $('.navbar li').find(escritorio).addClass('active');
        } else if(/noticias/.test(loc)) {
            $('.navbar li').find(noticias).addClass('active');
        } else if(/contato/.test(loc)) {
            $('.navbar li').find(contato).addClass('active');
        };
    });
});

还有其他方法或最好/最简单的方法吗?

2 个答案:

答案 0 :(得分:1)

您的页面包含方法非常危险,因为我基本上可以访问您服务器上的任何php文件。

我建议使用包含所有允许的页面的数组,例如:

$pages = array('home', 'about', 'contact');
$current_page = '';

//Default page
if(!isset($_GET['p']) || empty($_GET['p'])){
$current_page = 'home';
}

现在,当您打印菜单时,您可以执行以下操作:

foreach($pages as $page){
echo '<li><a href=""';
if($page == $current_page) echo ' class="active"';
echo '></a></li>';
}

您可以展开您的网页数组,以包含titlemeta标记等。 例如:

$pages = array(
'home' => array('title' => 'Home', 'meta_description' => 'Bla Bla Bla'),
'about' => array('title' => 'About Us', 'meta_description' => 'Bla Bla Bla')
);

答案 1 :(得分:1)

由于您使用的是jQuery,请查看jQuery&#39; s load function。使用load你可以指定一个html元素(通常是div),你可以在其中加载页面,如下所示:

$("#myDiv").load("/my/page/folder/page.html");

要处理菜单,您需要这段代码:

// Select all menu links and attack event handler on them
$(".navbar li a").on("click", function(event){
  // This stop the link from loading into the browser tab(we want it to load in a div)
  event.preventDefault();
  // Remove any previous highlight
  $(".active").removeClass("active");
  // Add highlight to the menu we clicked
  $(this).addClass("active");
  // Load the link into "myDiv"
  $("#myDiv").load(this.href);
});

您可能需要调整此代码,我还没有对其进行测试,但这是一般的工作方式。

注意:在您加载的页面中,使用jQuery的加载功能,您只需要内容而不是整个HTML结构。

如果您只想加载部分页面,可以这样:

$("#myDiv").load("/my/page/folder/page.html #container");
相关问题