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 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计