0

我正试图让我的计数器,嗯,计数。我正在尝试使用以下内容在显示的每一秒帖子中添加一个类名(偶数):

<?php
        global $paged;
        global $post;
        $do_not_duplicate = array();
        $categories = get_the_category();
        $category = $categories[0];
        $cat_ID = $category->cat_ID;
        $myposts = get_posts('category='.$cat_ID.'&paged='.$paged);
        $do_not_duplicate[] = $post->ID;
        $c = 0;
        $c++;
        if( $c == 2) {
            $style = 'even animated fadeIn';
            $c = 0;
        }
        else $style='animated fadeIn';
        ?>

<?php foreach($myposts as $post) :?>
   // Posts outputted here
<?php endforeach; ?>

我只是没有得到even输出的类名。唯一输出的类名是animatedFadeIn类(来自我的 if 语句的 else 部分)现在添加到每个帖子中

4

3 回答 3

1

查看模数运算符

此外,将您的偶数/奇数支票移动到您的帖子循环中。

<?php $i = 0; foreach($myposts as $post) :?>
    <div class="<?php echo $i % 2 ? 'even' : 'odd'; ?>">
        // Posts outputted here
    </div>
<?php $i++; endforeach; ?>
于 2013-03-18T15:41:40.473 回答
0

从您的代码的这一部分:

    $c = 0;
    $c++;
    if( $c == 2) {
        $style = 'even animated fadeIn';
        $c = 0;
    }
    else $style='animated fadeIn';

您需要将增量和if-else块放在foreach循环内。像这样:

<?php foreach($myposts as $post) :
    $c++;
    if( $c % 2 == 0) {
        $style = 'even animated fadeIn';
        $c = 0;
    }
    else $style='animated fadeIn'; ?>
   // Posts outputted here
<?php endforeach; ?>
于 2013-03-18T15:43:17.713 回答
0

问题是您没有在 else 语句中将计数器设置回 2。

if( $c == 2) {
  $style = 'even animated fadeIn';
  $c = 0;
} else {
  $style='animated fadeIn';
  $c = 2;
}

话虽如此,您也可以像其他人提到的那样使用模数,或者干脆这样做:

//outside loop
$c = 1;


//inside loop
if ($c==1)
  $style = 'even animated fadeIn';
else
  $style='animated fadeIn';
$c = $c * -1;

甚至更短

//outside
$c = 1;

//inside
$style = (($c==1)?'even':'').' animated fadeIn';
$c = $c * -1;
于 2013-03-18T15:46:02.897 回答