使Twitter Bootstrap导航栏链接处于活动状态 [英] Make Twitter Bootstrap navbar link active

查看:102
本文介绍了使Twitter Bootstrap导航栏链接处于活动状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在加粗显示的Twitter Bootstrap导航栏中,活动链接的标准方法是什么?显而易见,链接通过获得活动"类而获得活动外观.例如,下面的Home链接处于活动状态.当我单击导航栏中的任何链接时,是否应该使用jQuery从li元素中删除所有类,然后将active类添加到我已确定的链接中?

What's the standard way to make the active link in a Twitter Bootstrap navbar bolded? It's clear that a link gains the active appearance by gaining the "active" class. For example, the Home link below is active. When I click any link in the navbar, should a use jQuery to remove all classes from li elements and then add the active class to the link I've id'd?

<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
</ul>

编辑:我加入了

<script type="text/javascript">
$('.nav li a').on('click', function() {
    alert('clicked');
    $(this).parent().parent().find('.active').removeClass('active');
    $(this).parent().addClass('active');
});
</script>

链接后的

.当我单击链接时出现警报,但是活动"类未添加到链接中.

after the links. The alert appears when I click a link, but the "active" class is not added to the link.

这是我所有的导航栏HTML:

Here's all of my navbar HTML:

<div class="navbar navbar-fixed-top">
    <div class="navbar-inner">
        <div class="container">
            <a class="brand" href="#">AuctionBase</a>
            <div class="nav-collapse">
                    <ul class="nav">
                        <li><a href="home.php">Search</a></li>
                        <li><a href="about.php">About</a></li>
                    </ul>
            </div>
        </div>
    </div>
</div>

推荐答案

您需要确保将 active 类设置为请求响应的一部分(随着页面加载),而不是在当用户单击链接以请求其他页面时.

You need to ensure that you set the active class as part of the request response (as the page loads) and not before ie when the user clicks a link to request a different page.

首先,您需要确定哪个navlink应该设置为活动的,然后将 active 类添加到<li>.代码看起来像这样

First you need to determine which navlink should be set as active and then add the active class to the <li>. The code would look something like this

由asker测试:

php文件中的HTML

<li>标记内调用php函数,并在链接目标请求uri中传递

Call a php function inline within the <li> markup passing in the links destination request uri

<ul class="nav">
    <li <?=echoActiveClassIfRequestMatches("home")?>>
        <a href="home.php">Search</a></li>
    <li <?=echoActiveClassIfRequestMatches("about")?>>
        <a href="about.php">About</a></li>
</ul>

PHP函数

简单的php函数需要比较传入的请求uri,如果与当前呈现的页面匹配,则输出 active

The php function simple needs to compare the passed in request uri and if it matches the current page being rendered output active class

<?php 

function echoActiveClassIfRequestMatches($requestUri)
{
    $current_file_name = basename($_SERVER['REQUEST_URI'], ".php");

    if ($current_file_name == $requestUri)
        echo 'class="active"';
}

?>

这篇关于使Twitter Bootstrap导航栏链接处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆