Wednesday, July 24, 2013

Apply Even and Odd classes for elements on, "while" or "for" loop

When we display list of elements using any looping, we need to add some two classes for differentiate one row from another. On this case we need use one extra variable, and increment it throw loop, then we can get '0' or '1' by mod(%) this value. So now we can have two different classes repeatedly like 'r0','r1'. And now write style for these two classes.

Example:
<style type="text/css">
Output
.list0{
background-color: #00B2C1;
}
.list1{
background-color: #50D4FF;
}
</style>
<html>
<title>Even and Odd classes for loopig elements</title>
<body>
<table cellspacing="0">
<tr>
<td>NO</td>
<td>Name</td>
</tr>
<?php $i=0; while($i<=10) { ++$i; ?>
<tr class="list<?php echo (++$x%2); ?>">
<td><?php echo $i; ?></td>
<td>Name <?php echo $i; ?></td>
</tr>
<?php } ?>
</body>
</html>


Note: Here we can use '$i' to mod. But most of cases we don't has this option, and more over here we wrote single line(++$x%2) to get mod value.

No comments:

Post a Comment

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...