无序列表中项目的交替背景颜色

时间:2010-02-28 05:45:53

标签: javascript jquery

我有一件物品。我想替代背景颜色 这是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> 

这是ma 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

1 个答案:

答案 0 :(得分:3)

一行版本:

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

两行版本:

$("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");
});