开发者

jQuery odd/even Selectors for Multiple Elements

I am using the following code to zebra strip a few tables on one page:

    $(".events-table tr:even").css("background-color", "#fff");
$(".events-tab开发者_开发知识库le tr:odd").css("background-color", "#efefef");

This is working just fine, but the even/odd intervals are applied to every table on the page. I would like each table to have the same pattern. Meaning, each table should start with the same colour on the first row, then same on the second row, for each table on the page.

Any suggestions?

Thx!


you could probably use a selector for the table and then find the rows to color, ie:

$(".events-table").each(function()
{
    $(this).find("tr:even").css("background-color", "#fff");
    $(this).find("tr:odd").css("background-color", "#efefef");
});


Use :nth-child() (:nth-child(odd) and :nth-child(even)) as opposed to :odd or :even

$("table.events-table tr:nth-child(even)").css("background-color", "#fff");
$("table.events-table tr:nth-child(odd)").css("background-color", "#efefef");

the :odd and :even are actually 0-based, meaning odd rows are 0,2,4, etc. and vice-versa and are used to get odd and even matches in the complete wrapped set.

Take a look at this Working Demo to demonstrate.

nth-child() performs the selection on a parent element basis.


The problem is that the .events-table tr selectors returns a list of trs independent of whether they belong to the same table. The :even and :odd selectors are applied to the complete list.

If you don't have an incredible big amount of tables you could just use ids rather than classes.

$("#events-table1 tr:even").css("background-color", "#fff");
$("#events-table1 tr:odd").css("background-color", "#efefef");
$("#events-table2 tr:even").css("background-color", "#fff");
$("#events-table2 tr:odd").css("background-color", "#efefef");


The :odd and :even selectors are jQuery-specific "extensions". As mentioned by bluenote, they seem to operate on a list of all elements of the targeted type (in your case, all tr in .events-table.

Alternatives include:

  • Constraining the selector to the table context by passing your table element as the second argument $('tr:odd', mytable).css({})

  • Using the "real" css nth-child selector $('.events-table tr:nth-child(even)').css() though beware of cross-browser compatibility issues.

  • Assigning an 'odd' or 'even' class to the appropriate rows and targeting that explicitly.


$("tr:odd").css("background-color", "#bbbbff");

will change odd rows for all the tables on the page, you can put another one for even


Try adding IDs to your tables and updating the CSS one table at a time.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜