admin 管理员组

文章数量: 1086019

I don't have a table or ul structure for this but I am using divs to display data. I need the background color of every other row to be black. I looked around but most options are for tables or list menus so a bit puzzled as to how to do this. Any idea?

My structure:

<div class="container">
     <div class="dataset">
         Thomas Jones
     </div>
     <div class="dataset">
         Edward Jones
     </div>
 <div class="dataset">
         Tommy Lee
     </div>
 <div class="dataset">
         Jenna Haze
     </div>
</div>

I don't have a table or ul structure for this but I am using divs to display data. I need the background color of every other row to be black. I looked around but most options are for tables or list menus so a bit puzzled as to how to do this. Any idea?

My structure:

<div class="container">
     <div class="dataset">
         Thomas Jones
     </div>
     <div class="dataset">
         Edward Jones
     </div>
 <div class="dataset">
         Tommy Lee
     </div>
 <div class="dataset">
         Jenna Haze
     </div>
</div>
Share Improve this question asked Sep 5, 2013 at 16:16 starbucksstarbucks 3,01610 gold badges43 silver badges53 bronze badges 2
  • 4 please share the html – Arun P Johny Commented Sep 5, 2013 at 16:16
  • 1 No need for JQuery, use CSS. – Vucko Commented Sep 5, 2013 at 16:18
Add a ment  | 

4 Answers 4

Reset to default 9

You can do with with just CSS(3) using :nth-child(odd) (or even):

div.dataset:nth-child(odd) {
    background: black;
}

jsFiddle example

i would go with CSS but in case you need it in jquery..then you can use :even or :odd selector.

try this

 $('div:even').css('background-color','black'); // or just background , selects all even divs.
 $('div:odd').css('background-color','black'); //selects all odd divs.

for just those divs having class dataset..add class selector to div. try this

 $('div.dataset:even').css('background','black');

Use even/odd css3 selector

HTML

<div>row1</div>
<div>row2</div>

CSS

div {
    width: 100px;
    height: 20px;
    border: 1px solid #ccc;
    color: #fff;
}

div:nth-child(odd) {
    background:red; 
}

div:nth-child(even) {
    background:black; 
}

http://jsfiddle/sheeban/vHGzw/

If you must use jQuery for this:

$(".dataset").each(function(index){
    if(index%2 == 0)
       $(this).css('background', 'black');
});

jsFiddle

or use $("div.dataset:even").css('background', 'black');

jsFiddle

本文标签: javascriptUsing JQuery how can I color every other row blackStack Overflow