qwr qwr
qwr qwr

Reputation: 1059

how do i user Jquery selector for odd and even rows generated by php code?

So basically i would like to color the comments from users so it look clear and separate. The comments is coming from the database, the php codes will generate the comments in a HTML page. And i am using CSS and Jquery as well. I have tried but my codes don't work, any idea?

HTML/PHP:

    <? 
for($i=0;$i<mysql_num_rows($comment);++$i)
{
$row = mysql_fetch_array($comment);
?>  
        <div class = "comment">
        <p> <? echo $row['c_content']; ?>  by <? echo $row['c_name']; ?> </p>
        </div>
        <?}?>

CSS:

.comment
{
    background-color:#fff;     
}

.alt
{
    background-color:#ccc;
}

Jquery:

$(document).ready(function(){
$(".comment:odd").addClass('alt');
});

So as you can see, I want the "odd" comment class have color #CCC, and the even have #FFF... Please help

Upvotes: 0

Views: 111

Answers (1)

dtbarne
dtbarne

Reputation: 8200

No need to use jQuery here. Use CSS:

.comment:nth-child(even) {
    background-color: #fff;
}

.comment:nth-child(odd) {
    background-color: #ccc;
}

Unrelated, but worth noting is that unless you're using both associate and numerical keys to access your mysql result, you should get into the habit of using mysql_fetch_assoc() instead of mysql_fetch_array() or you are always using twice as much memory.

Upvotes: 2

Related Questions