简体   繁体   English

将css类添加到列表项(jQuery中的最后一个除外)

[英]Add css class to list items except last in jQuery

I have an unordered list which values are generated from a database using php and mysql. 我有一个无序列表,这些值是使用php和mysql从数据库生成的。

<div id="articles">
    <ul>
        <?php foreach ($articles as article) { ?>
            <li><a href="/articles/<?php echo $article['name']; ?>"> <?php echo $article['name']; ?> </a> </li>
        <?php } ?>
    </ul>
</div>

I'd like to use jQuery to add a css class to every item in that list except the last one 我想使用jQuery向该列表中的每个项目(最后一个项目除外)添加一个CSS类

 //then you can select all `li` elements under `#articles` except the last one like jQuery(function($) { $('#articles li:not(:last)').addClass('myclass') }) 
 .myclass { background-color: lightgrey; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="articles"> <ul> <li><a href="/articles/1">1</a></li> <li><a href="/articles/2">2</a></li> <li><a href="/articles/3">3</a></li> </ul> </div> 


You can do it with css only 您只能使用CSS来做

 #articles li { background-color: lightgrey; } #articles li:last-child { background-color: white; } 
 <div id="articles"> <ul> <li><a href="/articles/1">1</a></li> <li><a href="/articles/2">2</a></li> <li><a href="/articles/3">3</a></li> </ul> </div> 

<div id="articles">
<ul>
    <?php 
         $count =count($articles);
         foreach ($articles as article) {
           $counter++;
            If($count==$counter)
                 $class='something';
             Else
                 $class='';
 ?>
               <li><a href="/articles/<?php echo     $article['name']; ?>"> <?php echo $article['name']; ?>     </a> </li>
        <?php
             }
         ?>
</ul>
</div>

Use class variable in li now. 现在在li中使用class变量。

You can achieve same thing using PHP also by adding one more condition in your code. 您还可以通过在代码中添加一个条件来使用PHP实现相同的目的。

foreach ($articles as $article) {
    if(end($articles) == $article) {
    ?>
       <li><a href="/articles/<?php echo $article['name']; ?>"> <?php echo $article['name']; ?> </a></li>
    <?php
    }
    else{ ?>
       <li class="myclass"><a href="/articles/<?php echo $article['name']; ?>"> <?php echo $article['name']; ?> </a></li>
   <?php
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM