douzhuan1432 2013-11-23 08:55
浏览 36
已采纳

如何使用php添加不同的CSS到最后的mysql查询结果

I'm retrieving 4 latest items from the database and show them in a list. My question is that how can I add a different HTML class to the last item?! for example,

<ul>
    <li class="list">number 1</li>
    <li class="list">number 2</li>
    <li class="list">number 3</li>
    <li class="list last-child">number 4</li> 
</ul>

how can I add last-child to the last item using php?

  • 写回答

3条回答 默认 最新

  • doulin2025 2013-11-23 08:56
    关注

    Instead of assigning a class using PHP, use :last-child pseudo instead

    ul.class_name li:last-child { /* This will target last li in the ul */
       /* Styles */
    }
    

    Demo

    Better assign a class to your ul element to distinguish with other ul elements in the same document.


    If you want to literally add the class to the DOM for some reason than you can use a counter variable with mysqli_num_rows (Here I assume you are atleast using mysqli_()).

    $counter = 0;
    $total_rows = mysqli_num_rows($query);
    
    while($throw_results = mysqli_fetch_array($query)) {
       $counter++; /* Increment the counter by 1 */
       if($total_rows == $counter) {
          /* Add class if total rows = counter value */
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?