开发者

Set two classes from array

开发者 https://www.devze.com 2023-01-02 18:21 出处:网络
I want to change the classes on every third output from a query: <?php $style_classes = array(\'box\',\'box\',\'box no_right_margin\');

I want to change the classes on every third output from a query:

    <?php
$style_classes = array('box','box','box no_right_margin');
$style_index = 0;
?>

I set this on the div:

<div <?php $k = $style_index%4; echo "class=$style_classes[$k]"; $style_index++; ?>>

On the third div I want the class to look like this:

<div class="box no_right_margin">

Right now it looks like开发者_C百科:

 <div class="box" no_right_margin>


You need to enclose the class names in quotes. Your script is actually outputting class=box no_right_margin. (I think the example you gave as the current output is not what the script is sending, but the view of the DOM from something like Firebug, which is showing the browser as only seeing the first class in the list)

So you could do this:

<div class="<?php $k = $style_index%4; echo $style_classes[$k]; $style_index++; ?>">

or even

<div class="<?php echo $style_classes[$style_index++ % 4]; ?>">


You should use %3 instead of %4, so you actually get indexes 0, 1 and 2.
And you need correct quotes in your HTML output:

<?php   echo '<div class="' . $style_classes[$k++ % 3] . '">';   ?>

Else your browser (Safari?) would probably correct it with a " at the wrong place, as shown in your example. Btw, it's better style to use hyphens for CSS class names, not underscores (unlike IDs).

0

精彩评论

暂无评论...
验证码 换一张
取 消