最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: Zebra striped table - Stack Overflow

programmeradmin1浏览0评论

I have two table on page and I am trying to give it zebra strip effect. It works fines but for second table tr taking count from first table. Due to this even tr bee the first tr.

Example of my work /

code I am using for this is below:

$('table tr:even:not(:first)').css('background-color','#ededed');

I have two table on page and I am trying to give it zebra strip effect. It works fines but for second table tr taking count from first table. Due to this even tr bee the first tr.

Example of my work http://jsfiddle/A9wpe/1/

code I am using for this is below:

$('table tr:even:not(:first)').css('background-color','#ededed');
Share Improve this question edited Jan 8, 2014 at 6:26 manman 5,1134 gold badges31 silver badges44 bronze badges asked Jan 8, 2014 at 6:23 Rakesh KumarRakesh Kumar 2,8651 gold badge22 silver badges36 bronze badges 1
  • see: stackoverflow./questions/15789526/… – ColinE Commented Jan 8, 2014 at 6:28
Add a ment  | 

5 Answers 5

Reset to default 3

Could always iterate through each table, acting on each independently:

$('table').each(function(){$(this).find('tr:even').css('background-color','#ededed')});

Or, if your users have recent browsers, you'd do this in CSS:

table tr:nth-child(even) {background-color: #ededed;}

Don't use jQuery for this. Use CSS instead

DEMO

.subPro-data tr:nth-child(even){
    background-color : #ededed;
}

DEMO With jQuery for old IE

.subPro-data tr.even{
    background-color : #ededed;
}

and

$('.subPro-data tr:even').addClass('even');

Point is you want to avoid selectors like this $('table#{tableID1} tr:even:not(:first), table#{tableID2} tr:even:not(:first)'). Its a nightmare of inefficiency, and ultimately its so plicated only because you are using the following mand: .css('background-color','#ededed');

Using .css adds those styles to the inline style attribute on the dom element. http://www.w3schools./css/css_howto.asp inline styles override almost all css rules. What you should be doing is just adding a class instead. That way the background color lives in a css rule and will naturally be in the right location in the css cascade.

This also means you can use a simple and sane selector like this $('.subPro-data tr:even').

Give id for both table and use jQuery below:

$('table#{tableID1} tr:even:not(:first), table#{tableID2} tr:even:not(:first)').css('background-color','#ededed');

Replace table id with {tableID1} and {tableID2}. See JSFiddle example.

$('table').each(function(index, value) { $(value).find('tr:even:not(:first)').css('background-color','#ededed');});

You can filter rows using :not(:first) and then apply nth-child(odd) rule. check DEMO here

$('table tr:not(:first):nth-child(odd)').css('background-color','#ededed');

发布评论

评论列表(0)

  1. 暂无评论