每隔三次添加一次类<;李>;通过Php

每隔三次添加一次类<;李>;通过Php,php,wordpress,Php,Wordpress,我在WordPress中获得动态帖子。但是我想在每三次之后添加类 像这样 <li></li> <li></li> <li class="last_child"></li> <li></li> <li></li> <li class="last_child"></li> 假设您是通过for循环创建它们,只需检查索引即可。大概是这样的: for

我在WordPress中获得动态帖子。但是我想在每三次
  • 之后添加类

    像这样

    <li></li>
    <li></li>
    <li class="last_child"></li>
    <li></li>
    <li></li>
    <li class="last_child"></li>
    

  • 假设您是通过for循环创建它们,只需检查索引即可。大概是这样的:

    for ($i=0; $i<$num_lis; $i++) {
        echo '<li'.($i % 3 == 2 ? ' class="last_child"' : '').'></li>';
    }
    

    假设您是通过for循环创建它们,您只需检查索引即可。大概是这样的:

    for ($i=0; $i<$num_lis; $i++) {
        echo '<li'.($i % 3 == 2 ? ' class="last_child"' : '').'></li>';
    }
    
    您只需使用CSS即可:

    li:nth-child(3n) { 
        /* Your styles here */
    }
    
    此外,Wordpress还内置了jQuery,因此您也可以使用

    $("ul li:nth-child(3n)").addClass("last_child");
    
    您只需使用CSS即可:

    li:nth-child(3n) { 
        /* Your styles here */
    }
    
    此外,Wordpress还内置了jQuery,因此您也可以使用

    $("ul li:nth-child(3n)").addClass("last_child");
    

    为什么不使用CSS“
    n子项”
    ?他没有指定这是用于CSS的。但如果是,我同意这将是最好的解决方案。为什么不使用CSS的第n个孩子呢?他没有指定这是用于CSS的。但是如果是,我同意这将是最好的解决方案。因为类可能不用于CSS,jQuery实际上为元素提供了类。因为类可能不用于CSS,jQuery实际上为元素提供了类。