dpus81500574 2013-06-13 12:52
浏览 46
已采纳

偶数/奇数确定CSS类

I've read a lot of information about the determination of a even/odd number and using it to change the class of a div.

In my case I want to switch the position of divs called MessagePicture and MessageText every new message posted.

  1. Picture left, Text right
  2. Picture right, Text left
  3. Picture left, Text right
  4. ect.

This is the code I am using to display the messages, I also included one of my tries to get the even/odd code to work.

Can anyone tell me what I should change to get it to work?

    <?PHP

    $Query =
    "
            SELECT
                ID,
                NameBox,
            MessageBox,
            Code
        FROM
            messages
            ORDER BY
                ID
            DESC LIMIT 10
    ";

    $Result = mysql_query($Query);

        if(!$Result)
            {
            echo 'ERROR: '.mysql_error();
            }

        else
            {
            if(mysql_num_rows($Result) == 0)
                {
                    echo 'No results';
                }

                else
                    {
                    $i = 0;
                $class = (++$i % 2) ? 'even' : 'odd';
                    while
                    ($Row = mysql_fetch_assoc($Result))

                        echo '

<div id="MessageWrapper">
    <div id="MessagePicture" class="'.$class.'">                                                                                
        <style>                                             
        #MessagePicture { 
        background-image: url(../../../Images/'.stripslashes($Row['Code']).'.png);  
        background-repeat: no-repeat; 
        background-position: center
        </style>
        </div>

    <div id="MessageText" class="'.$class.'">

        <div id="MessageTitle">

            <h1>'.$Row['NameBox'].'</h1>

        </div>

        <div id="MessageContent">                                                   
            <p>'.nl2br($Row['MessageBox']).'</p>
        </div>

    </div>

</div>  

';}}}?>
  • 写回答

2条回答 默认 最新

  • douyin8623 2013-06-13 12:58
    关注

    Your $i always stays 0. Add $i++ in the while loop to increment it.

    You can do that in one line:

    $class = ($i++ % 2 == 0) ? 'even' : 'odd';
    

    Full Example:

    $i = 0;
    while ($Row = mysql_fetch_assoc($Result)) {
      $class = ($i++ % 2 == 0) ? 'even' : 'odd';
      //echo ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?