简体   繁体   English

使用php mysql为div分配不同的类名

[英]Assign different class names to div with php mysql

I have four divs in one page which are styled so that it has four alternating colours. 我在一个页面中有四个div,它们的样式使它有四种交替的颜色。 And the even div ie 2nd and 4th have an extra class name 'r' like this. 偶数div即第2和第4个有一个额外的类名'r'。

<div class="x-1 liner"><div>
<div class="x-2 liner r"><div>
<div class="x-3 liner"><div>
<div class="x-4 liner r"><div>

The results are pulled from the database, I can use the modulus operator ( % ) to assign alternating colours for two rows as shown in here but how can I do this for four rows and also add 'r' to the even divs? 结果从数据库中抽取的,我可以使用模运算符( % ),如图分配交替的颜色为两列在这里 ,但我怎么能做到这一点的四行,并添加“R”到偶数的div?

As kojow7 says you can use % 2 and % 4 , see this code: 正如kojow7所说,您可以使用% 2% 4 ,请参阅以下代码:

<?php

for($i = 1; $i <= 4; $i++) {
  echo "div class='x-$i liner";
  if($i % 2 == 0) echo ' r';
  if($i % 4 == 0) echo ' color';
  echo "'><div>\n"; 
}   

?>

Output: 输出:

div class='x-1 liner'><div>
div class='x-2 liner r'><div>
div class='x-3 liner'><div>
div class='x-4 liner r color'><div>

EDIT: With a foreach should be like this, but I don't know what values have $data 编辑:使用foreach应该是这样的,但我不知道有什么值有$data

<?php

$i = 1;

foreach($data as $row) {
  echo "div class='x-$i liner";
  if($i % 2 == 0) echo ' r';
  if($i % 4 == 0) echo ' color';
  echo "'><div>\n"; 
  $i++;
}   

?>

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

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