V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
cevincheung
V2EX  ›  PHP

如何优雅的处理 [当前 active] 的 A 标签

  •  
  •   cevincheung · 2016-03-23 20:00:10 +08:00 · 2313 次点击
    这是一个创建于 2953 天前的主题,其中的信息可能已经有所发展或是发生改变。
    @section('nav')
    <ul class="nav menu">
            <li class="active"><a href="index.php"><span class="glyphicon glyphicon-dashboard"></span> 用户中心首页</a></li>
            <li><a href="transfer.php"><span class="glyphicon glyphicon-th"></span> 充值 /提现</a></li>
            <li><a href="withdraw-history.php"><span class="glyphicon glyphicon-stats"></span> 提现记录</a></li>
            <li><a href="profile.php"><span class="glyphicon glyphicon-user"></span> 账户 /修改密码</a></li>
            <li><a href="certificate.php"><span class="glyphicon glyphicon-credit-card"></span> 实名认证</a></li>
            <li role="presentation" class="divider"></li>
            <li><a href="logout.php"><span class="glyphicon glyphicon-log-out"></span>退出登录</a></li>
    </ul>
    @stop
    

    难道非要一个个的 if...echo..active 么?

    6 条回复    2016-03-24 14:54:56 +08:00
    SUBMAIL
        1
    SUBMAIL  
       2016-03-23 21:52:45 +08:00
    <body id="glyphicon-dashboard">
    <ul class="nav menu">
    </body>

    #glyphicon-dashboar .nav .glyphicon-dashboard{}

    这样处理呢?
    cevincheung
        2
    cevincheung  
    OP
       2016-03-23 22:15:00 +08:00
    @SUBMAIL
    没有更好的方法了么- -
    SoloCompany
        3
    SoloCompany  
       2016-03-23 23:07:43 +08:00
    莫当真

    ob_start();

    $nav = ob_get_contents();
    ob_end_clean();
    echo str_replace("<li><a href=\“$page\”", “<li class=“ active"><a href=\“$page\”", $nav);
    oott123
        4
    oott123  
       2016-03-23 23:17:48 +08:00
    你应该把整个导航写成一个循环……这样就稍微优雅一点了。
    iNaru
        5
    iNaru  
       2016-03-24 09:56:05 +08:00   ❤️ 1
    用 js
    ```javascript
    (function(n){
    [].forEach.call(document.querySelectorAll('.nav a'), function(a, i){
    a.parentNode.classList[(location.href.indexOf(a.href) == 0 ||
    (n == '' && i == 0) ? 'add' : 'remove')]('active');
    });
    })(location.href.split('/').pop().split(/[\?#&]/).shift());
    ```
    cevincheung
        6
    cevincheung  
    OP
       2016-03-24 14:54:56 +08:00
    @iNaru
    好吧,用 js 貌似也是个不错的选择。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1221 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:17 · PVG 07:17 · LAX 16:17 · JFK 19:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.