开发者

How to target multi-class element with jQuery

I have the following two tables and jQuery:

<table class="grid" />
<table class="grid custom" />

 $('.grid tr:even').addClass('alt');

What's happening here is that both tables are being targeted by jQuery. The first table is fine as the even row is being selected, however the odd is being selected on the second table.

table 1 (grid)

row 1

row 2 - backgroun开发者_JAVA技巧d color (this is right)

table 2 (grid custom)

row 1 - background color (this is wrong)

row 2

How can I fix this?


http://jsfiddle.net/Ftk5n/

The problem is that the $('.grid tr:even') selector is applying the :even criteria to the set of all rows returned by .grid tr. You want the :even to be applied on a per-table basis.

Incidentally, you can do this purely in CSS: http://jsfiddle.net/ahf9q/1/

Edit: Turns out jQuery has the nth-child selector that operates just like CSS does. If you're set on doing this in jQuery rather than CSS, you could do:

$('.grid tr:nth-child(odd)').addClass('alt');

http://jsfiddle.net/Ftk5n/2/


$('.grid').each(function(){
    $(this).find("tr:even").addClass('alt');
});

That should do it.


Try this

$('.grid').each(function(){
    $("tr:even", this).addClass('alt');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜