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条)

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器