2012-12-30 21 views
0

我想在每兩個項目之後的while循環中添加一個div標籤。在一個while循環中包裝項目

我正在嘗試使用下面的代碼,但它在最後增加了一個額外的空<div></div>

$i = 0; 
while (have_posts()) : the_post(); 
    $i++; 
    if ($i == 1){$output .= "<div>";} 

    if ($i % 2 == 0){$output .= "</div><div>";} 

    endwhile; 
if ($i % 2 != 0){$output .= "</div>";} 
+0

你的命令的項目細節在哪裏?它是在if語句還是之前? – shashwat

+0

使用$ i的目的是什麼? – Techie

回答

1

你需要用邏輯了。因爲如果你有0個元素,你不需要任何包裝。如果你甚至有元素,最後你不需要額外的包裝。

我在這裏增加了兩個新功能,我想這很清楚他們的工作:div_open()div_close()。下面修改你的僞代碼,然後應該概述它是如何工作的:

if (have_posts()) 
{ 

    div_open(); 

    for ($counter = 0; have_posts(); $counter++) 
    { 

     the_post(); 

     ... 

     if ($counter && have_posts() && $counter % 2 == 0) 
     { 

      div_close(); 

      div_open(); 

     } 

    } 

    div_close(); 

} 
1

嘗試增加你的額外</div><div>在下次迭代的開始:

$i = 0; 
$div = ''; 
while (have_posts()) : the_post(); 
    $i++; 
    $output .= $div; 
    if ($i == 1){$output .= "<div>";} 

    if ($i % 2 == 0){$div = "</div><div>";} 
    else {$div = '';) 

    endwhile; 
if ($i % 2 != 0){$output .= "</div>";}