简体   繁体   English

PHP速记变量切换表行背景色

[英]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. 我最近在php中使用以下速记来定义表格行背景色。

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. 发生的是$i = !$i意味着$ i不能等于$ i,因此,如果$ i第一次为true,则它为false,反之亦然。 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. 当然, if每次都会检查值true or false ,从而每隔一次输出样式并获得其他背景效果。

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. 我没有得到$ i!= $ i的逻辑,但是如果我了解到您想要不同的颜色来交替TR,则可以在CSS级别完成。 Use CSS - nth Property. 使用CSS-第n个属性。

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 注意: 使用2n + 02n + 1作为替代-从第一行+ 2或第二行+ 2开始

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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