Easiest way to alternate row colors in PHP/HTML?

前端 未结 19 1857
無奈伤痛
無奈伤痛 2020-12-01 03:41

Here\'s a PHP example of mine. Can anyone find a shorter/easier way to do this?


    
相关标签:
19条回答
  • 2020-12-01 04:20

    Using CSS3 you can do something like this:

    div:nth-child(odd)
    {
      background-color: red
    }
    

    But better not use that for a few years if you actually want your users to see the color...

    0 讨论(0)
  • 2020-12-01 04:20

    It's short enough as it is, but I would probably wrap it into some helper function with a clear name. That way it's more obvious what's going on and you won't have to repeat that logic in all templates where you need it.

    0 讨论(0)
  • 2020-12-01 04:24

    i always name my zebra rows "row0" and "row1" - this makes the code a bit simpler.

    <?php  // you should always use the full opening tag for compatibility
    $i = 0;
    foreach ($rows as $row) {
        echo '<tr class="row' . ($i++ % 2) . '">...</tr>';
    } 
    ?>
    
    0 讨论(0)
  • 2020-12-01 04:24

    Just for fun

    Assuming you can use CSS3 selectors you can do something like

    <div class="posts">
    <? foreach($posts as $post){?>
        <div>
            <?=$post?>
        </div>
    <? }?>
    </div>
    
    <style>
        div.posts div:odd{background-color:red;}
    </style>
    

    Even with CSS2 support and mootools (javascript library) you can substitute the style with this javascript

    <script type="text/javascript">
        // obviously this script line should go in a js file in a onload (or onDomReady) function
        $$('div.posts div:odd').setStyle('background-color','red');
    </script>
    

    If you don't have anything but php a it you can simplify a bit yous code using an array

    <? $isodd=array('','odd');
       $c=0;
       foreach($posts as $post){?>
        <div class="<?=$isodd[$c++%2]?>">
            <?=$post?>
        </div>
    <? }?>
    
    0 讨论(0)
  • 2020-12-01 04:25

    Smarty has it inbuilt:

    {section name=rows loop=$data}
    <tr class="{cycle values="odd,even"}">
       <td>{$data[rows]}</td>
    </tr>
    {/section}
    

    So does Django:

    {% for o in some_list %}
        <tr class="{% cycle 'row1' 'row2' %}">
            ...
        </tr>
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-01 04:28
        <?php   ($i%2==1) ? $bgc='#999999' : $bgc='#FFFFFF'; ?>
        '<div bgcolor=" bgcolor='.$bgc.'">';
    
    0 讨论(0)
提交回复
热议问题