简体   繁体   中英

PHP shorthand variable toggle for table row background colors

I've been using the following shorthand in php lately for defining table row background colors.

Are there are caveats to using this method , other than perhaps obscurity?

 <?php $style = 'style="background-color:#CCC;"'; ?>
 <tr <?php if ($i = !$i) echo $style; ?>>
      <td><input /></td>
 <tr>

What's happening is $i = !$i means $i cannot equal $i, so if $i is true the first time, it becomes false, and vice versa. The if of course checks the value true or false each time, thereby outputting the style every other time and obtaining the every-other background effect.

I did not get your logic of $i != $i, but still if i understood that you want different colors for alternating TR , it can be done at css level. Use CSS - nth Property.

try :

tr:nth-child(odd) {
    background: red;
}

tr:nth-child(even) {
    background: blue;
}

OR

tr:nth-child(2n+1) {
     background: yellow;
} 

Note: Use 2n+0 or 2n+1 for alternate - starting first row + 2, or 2nd row + 2

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