2010-02-28 84 views
1

我有一個UI項目。我想交替出現的背景顏色 下面是HTML無序列表中項目的交替背景顏色

<html> 
    <head> 
    <title>JQuery Problem 1</title> 
    <script type="text/javascript" src="jquery-1.4.min.js"></script> 
    <script type="text/javascript" src="problem1.js"></script> 
    </head> 
    <body> 
    <ol> 
     <li>Comp 250 
     <ul> 
      <li>HTML</li> 
      <li>CSS</li> 
      <li>CGI</li> 
      <li>PHP</li> 
      <li>JavaScript</li> 
     </ul> 
     </li> 
     <li>Comp 345 
     <ul> 
      <li>Objects and classes</li> 
      <li>Static and constant members</li> 
      <li>Operator overloading</li> 
      <li>Templates</li> 
      <li>Inheritance</li> 
      <li>Polymorphism</li> 
     </ul> 
     </li> 
     <li>Comp 431 
     <ul> 
      <li>Perl language</li> 
      <li>File uploads and downloads</li> 
      <li>AJAX and JSON</li> 
      <li>Java Servlets</li> 
      <li>JSP</li> 
     </ul> 
     </li> 
    </ol> 
    </body> 
</html> 

這裏是馬的JQuery

$(document).ready(function() 
{ 


    $("ol > li").css({margin: "1em", fontWeight: "bold"}); 
    $("ol li li").css({fontWeight: "normal"}); 
    $("ul li").css('border', '1px solid white'); 

    $("ul li").hover(function() 
     { 
      $(this).css('border', '1px solid red'); 
     }, 
     function() 
     { 
      $(this).css('border', '1px solid white') 
     }); 


}); 

現在我想交替,在UL中的第一項應始終#FDD和第二#FFD

回答

3

一個行版本:

$("ol > li").filter(":nth-child(odd)").css("background", "#FDD") 
    .end().filter(":nth-child(even)").css("background", "#FFD"); 

兩線VERSI於:

$("ol > li:nth-child(odd)").css("background", "#FDD"); 
$("ol > li:nth-child(even)").css("background", "#FFD"); 

或使用each()

$("ol > li").each(function(i, val) { 
    $(this).css("background", i & 1 ? "#FFD" : "#FDD"); 
});