admin管理员组

文章数量:1334665

<table>
    <thead>
        <tr>
            <td>sf</td>
        </tr>
        <tr>
            <td>sf</td>
        </tr>
        <tr>
            <td>sf</td>
        </tr>
        <tr>
            <td>sf</td>
        </tr>
    </thead>
</table>


.red {
  background-color: red;
}
.green {
  background-color: green;
}

How can i make automatically add class red and green for TR with jQuery?

LIVE EXAMPLE: /

<table>
    <thead>
        <tr>
            <td>sf</td>
        </tr>
        <tr>
            <td>sf</td>
        </tr>
        <tr>
            <td>sf</td>
        </tr>
        <tr>
            <td>sf</td>
        </tr>
    </thead>
</table>


.red {
  background-color: red;
}
.green {
  background-color: green;
}

How can i make automatically add class red and green for TR with jQuery?

LIVE EXAMPLE: http://jsfiddle/2Htwx/

Share Improve this question asked Feb 24, 2012 at 13:54 Gryz OsheaGryz Oshea 3613 gold badges8 silver badges17 bronze badges 1
  • 1 $('tr').addClass('red').addClass('green')? – user684934 Commented Feb 24, 2012 at 13:55
Add a ment  | 

6 Answers 6

Reset to default 4
$('tr:odd').addClass('red');
$('tr:even').addClass('green');​

Assuming you want every other row red or green, as per your JS-fiddle. Note that this is within each table, so you won't see red/green/red across ALL table rows.

If you want that, try this:

var oddFilter = function(index) {
     console.log(index);
  return (index % 2) == 1;
},
 evenFilter = function(index) {
     console.log(index);
  return (index % 2) == 0;
}

$('tr').filter(oddFilter).addClass('red').end()
       .filter(evenFilter).addClass('green');​

Note that <thead>, <tfoot> etc can still mess up the display, since that moves rows around the display.

You don't need JavaScript to acplish this 'table-striping' effect. Use of the CSS nth-child selector will do the trick

thead tr {
    background: green; /* Set all tr elements to green */
}

thead tr:nth-child(even) {
    background: red; /* Override the colour for just the even ones */
}

Note: This selector is not supported in older browsers. IE8 and down.

Further reading on CSS nth-child:

  • http://css-tricks./how-nth-child-works/

You mean like this?

$(document).ready(function() {
     var class = "";
     $("tr").each(function(idx, elem) {
        class = (idx % 2 == 0)?"red":"green";
        $(elem).addClass(class);
     });
});

Could you please explain "automatically"? You mean at page ready event?

Maybe somthing like this:

$(document).ready(function (){
    $("tr:odd").css("background-color", "#f00");
    $("tr:even").css("background-color", "#0f0");
});

Here's the simplest method:

$("tr").addClass("red");

try this

var trs = jQuery('tr');
trs.filter(':even').addClass('red');
trs.filter(':odd').addClass('green');

to not selecting two-times every tr

本文标签: javascriptAutomatically add class with jQueryStack Overflow