简体   繁体   English

当我提前知道颜色和表格长度的行数时如何在表格中交替显示多行颜色

[英]how to alternate multiple row colors in table when i know number of rows to color and table length in advance

Im trying to alternate colors for multiple rows in a table. 我正在尝试为表中的多行替换颜色。 In advance i know the number of rows that i want to highlight, for example an array(8,8,9) tells me i want the first 8 rows one color and the next eight rows an alternating color and the last nine rows the first color again. 事先我知道要突出显示的行数,例如array(8,8,9)告诉我,我希望前8行使用一种颜色,而后8行使用交替颜色,而后9行使用第一种颜色再次上色。 he table length is 25 rows. 表格长度为25行。 My tables will change and my rows that i want colored can be array(4,4,5,5,5) for example. 我的表将更改,并且我要着色的行可以是array(4,4,5,5,5)。 what is the best way of doing this in javascript or is there a jquery solution. 用javascript做到这一点的最佳方法是什么,还是有jquery解决方案? I tried doing loops to no avail. 我试图做循环无济于事。

CSS is enough to do this. CSS足以做到这一点。 No need of javascript and jQuery. 不需要javascript和jQuery。

tr:nth-child(even) {
   background-color: blue;
}
tr:nth-child(odd) {
   background-color: green;
}

Refer LIVE DEMO 请参考现场演示

Something like this will work: 这样的事情会起作用:

var arr = [8, 8, 9];

var $tr = $('table tr');
var index = 0;

$.each(arr, function(i, el) {
    index = i > 0 ? arr[i - 1] + index : 0;
    $tr.slice(index, index + el).addClass(i % 2 ? 'even' : 'odd');
});

The key is slice method to apply styles to specified tr ranges. 关键是将样式应用于指定的tr范围的切片方法。

Demo: http://jsfiddle.net/39QvX/ 演示: http//jsfiddle.net/39QvX/

Or another version using for loop: 或使用for循环的另一个版本:

for (var index = 0, i = 0; i < arr.length; index += arr[++i - 1] || 0) {
    $tr.slice(index, index + arr[i]).addClass(i % 2 ? 'even' : 'odd');
}

Demo: http://jsfiddle.net/39QvX/2/ 演示: http//jsfiddle.net/39QvX/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM