简体   繁体   中英

Alternating table row background colors on a dynamic table

I have a table generated by a foreach loop.

Before the loop, I create $iteration = 0 . At the beginning of the loop it increments $iteration .

Then I do this:

if($iteration % 2 == 0) { 
  $greyRow = 'css for a grey row'; 
}

I've only three rows, at max, to test this with, but it seems that it greys the 2nd and 3rd row under the current rule, rather than only the second.

This following will add a grey class for even rows.

echo '<tr', ($iteration & 1 ? ' class="grey"': ''), '>';

Note

This uses a bitwise operator . It's a micro-optimization but far more optimal than the modulus operator (although notoriously used in these cases).

Also, I would encourage you to utilize CSS classes for even and odd rows versus inline styles or just toggling a single class (ie grey ).

echo '<tr class="', ($iteration & 1 ? 'even': 'odd'), '">';

Perhaps you also need to have an else statement to set back to the other color on the odd rows. Not quite sure without seeing more of your implementation.

if ($iteration % 2 == 0) {
    $css = 'css for a grey row';
} else {
    $css = 'css for a white row';
}

I like to do this kind of thing..

<style type="text/css">
.odd td { background: #eee; }
</style>
<tr class="<?= ++$iteration % 2? 'odd' : 'even'; ?>">....</tr>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM