Add different class to even and odd divs

2020-08-09 07:03发布

I have a block of PHP code that looks like this:

$flag = false;
if (empty($links))
{
    echo '<h1>You have no uploaded images</h1><br />';
}

foreach ($links as $link)
{   
    $extension  = substr($link, -3);
    $image_name = ($extension == 'peg') ? substr($link, -15) : substr($link, -14);  

    ($delete_submit) ? deleteImage('.' . $image_name, $link) : '';

    echo '<div>';
        echo '<table>';

        echo '<tr><td class="fullwidth"><a class="preview_img" href="' . $link . '"><img src="' . $link . '" title="Click to enlarge" width="300" class="thumb" /></a></td></tr>';

        echo '<tr><td><span class="default">Direct:</span>&nbsp;';
        echo '<input type="text" readonly="readonly" class="link-area" onmouseover="this.select();" value="' . $link . '" />'; 
        echo '</td></tr>';

        echo ($flag) ? '<hr /><br>' : '';

        echo '</table>';
        echo '<br>';
    echo '</div>';

    $flag = true;
}

I want the <div> to include a different class based on if it is even or odd. If it is even, it gets X class, if it's odd it gets Y class.

How do I do this in my case? I'm totally clueless and I don't know how to start!

标签: php html css
8条回答
Bombasti
2楼-- · 2020-08-09 07:29

If you're working on a prototype site, you could always implement a pure CSS solution:

div:nth-child(even) { /* Apply even class rules here */ }
div:nth-child(odd) { /* Apply odd class rules here */ }

The reason I recommend that you only use this for prototype sites is because the compatibility for :nth-child does not support IE8 or below.

查看更多
祖国的老花朵
3楼-- · 2020-08-09 07:29

Try something like this

$count = 0;
foreach($links as link) {
  $count++;
  print ($count % 2 == 1) ? "odd" : "even"; 
}
查看更多
登录 后发表回答