dpdp42233 2011-03-24 22:40
浏览 23
已采纳

如何重构这些if语句?

I have this code:

<div id="menu">
    <ul>
        <li><span id="menulabel">Your Languages</span></li>
        <?php
        $hotClass = '';
        $newClass = '';
        $topClass = '';
        if ($sort == 'hot')
            $hotClass = 'active';
        else if ($sort == 'new')
            $newClass = 'active';
        else if ($sort == 'top')
            $topClass = 'active';
        ?>
        <li><a id="Hot" href="index.php?sort=hot&page=1" class="<?php echo $hotClass; ?>">Hot</a></li>
        <li><a id="New" href="index.php?sort=new&page=1" class="<?php echo $newClass; ?>">New</a></li>
        <li><a id="Top" href="index.php?sort=top&page=1" class="<?php echo $topClass; ?>">Top</a></li>
    </ul>
</div>

Depending on which sorting the page is using a different menu item is highlighted to show the user. However, I really dislike this code because the class is empty instead of not present when the list item is not active. Also, every if statement does basically the same thing. Is it possible to refactor this in to something more elegant and readable? Thanks.

  • 写回答

7条回答 默认 最新

  • douyun3631 2011-03-24 22:43
    关注

    You might consider using a ternary here...

    <div id="menu">
        <ul>
            <li><span id="menulabel">Your Languages</span></li>
            <li><a id="Hot" href="index.php?sort=hot&page=1" class="<?php echo ($sort == 'hot') ? 'active' : '' ?>">Hot</a></li>
            <li><a id="New" href="index.php?sort=new&page=1" class="<?php echo ($sort == 'new') ? 'active' : '' ?>">New</a></li>
            <li><a id="Top" href="index.php?sort=top&page=1" class="<?php echo ($sort == 'top') ? 'active' : '' ?>">Top</a></li>
        </ul>
    </div>
    

    definitely saves a lot of code

    In case you're not familiar with the Ternary Operator

    (condition) ? 'result if true' : 'result if false'
    

    EDIT

    As Matijs Points out

    you could even put the entire class declaration inside the operator to avoid ending up with class=""

    <li><a id="Hot" href="index.php?sort=hot&page=1" <?php echo ($sort == 'hot') ? 'class="hot"' : '' ?> >Hot</a></li>`
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?