[英]PHP How to add specific class to last echoed <li> in while loop
在while循環中從數據庫中回顯結果,以便我可以一次回顯5個結果。 目前已經將標准字符串放入循環中以便進行測試。 <li>
元素的樣式具有border-bottom
屬性。 是否可以讓最后的結果回顯(數字5)以應用另一個將排除邊界的類?
$i = 1;
while($i <= 5) {
// On the 5th, change the class here to rule out the border-bottom.
echo "<li>jQuery &HTML5 audio player.</li>";
$i++;
}
那么,在那里的某個地方,拋出if語句? 抱歉。 這可能真的很簡單,但是已經漫長了一天
您能否根據計數器使用循環和輸出內部的簡單檢查?
<?php
$i = 1;
while($i <= 5)
{
if($i<5)
{
echo "<li>jQuery &HTML5 audio player.</li>";
}
else
{
echo "<li class='fluffeh'>jQuery &HTML5 audio player.</li>";
}
// On the 5th, change the class here to rule out the border-bottom.
$i++;
}
?>
或者,如果您希望每五分之一都不同,則可以執行以下操作:
<?php
$i = 1;
while($i <= 10)
{
if($i%5!=0)
{
echo "<li>jQuery &HTML5 audio player.</li>";
}
else
{
echo "<li class='fluffeh'>jQuery &HTML5 audio player.</li>";
}
// On the 5th, change the class here to rule out the border-bottom.
$i++;
}
?>
<?php
$i = 1;
while($i <= 5){
$class = "";
if($i===5)
$class = " class=\"last\"";
echo "<li$class>jQuery &HTML5 audio player.</li>"; // On the 5th, change the class here to rule out the border-bottom.
$i++;
}
當然,這是一個封閉問題的盲目答案,如果您遵循其他人的回答建議,您會做得更好。
與其總是使用數字5作為占位符,不如計算數組中的元素可能會更好,如果是最后一個,則省略該行。
$elementsCount = count($elements);
for ($index = 0; $index < $elementsCount; ++$index) {
$class = $index == $elementsCount - 1 ? 'lastElement' : 'standardElement';
echo '
<li class="', $class, '">', $elements[$index], '</li>';
}
您已經有一個計數器,您的變量$ i。 您計數的變量$ i知道何時到達第5個循環以結束循環。
您也可以將它用於if-或其他語句,以便在第三元素或secend元素或其他東西中執行某些操作,例如,當$ i計數為4時,它應該輸出其他類或執行函數或其他操作。
您所要做的就是詢問何時到達5循環時插入一個類:
<?php
$class = null;
$li_element = null;
for($i=0;$i<=5;$i++)
{
if($i==5)
{
$class="last_element";
}
$li_element .= '<li '.$class.'>...</li>';
}
echo '<ul>'.$li_element.'</ul>';
如果您不想在代碼中添加太多行,也可以執行以下操作:
$i = 1;
while ($i<= 5) {
echo ($i < 5) ? "<li>jQuery &HTML5 audio player.</li>" : "<li class='someclass'>jQuery &HTML5 audio player.</li>";
$i++;
}
作為“某類”您要應用於最后一個li的樣式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.