I want to add alternating colors to rows in a table, but instead of changing color every other row I want to switch color when the data in the first column changed compare to the row above. For example in the ta开发者_运维技巧ble below, the first two row would have the same color since the first fields are both "1", and the third row would have a different color. I'm looking for a solution without third-party libraries like jquery.
1 | A 1 | B
2 | C 3 | D 4 | EHere's one way of doing it: jsfiddle demo
This little chunk of code is pretty nice if your table is 1 dimensional:
(function(){
var trs = document.getElementById('thetable').getElementsByTagName('tr');
var last, toggle = false;
for(var i = 0; i < trs.length; i++){
var tds = trs[i].getElementsByTagName('td');
toggle ^= last != tds[0].innerText;
trs[i].style.backgroundColor = toggle ? '#AAAACC' : '#CCDDCC';
last = tds[0].innerText;
}
})();
JSFiddle
If you have tables within your table some modifications would need to be made.
If the rows are already sorted, you could just cycle through them and assign classes as needed:
var trs = document.getElementById('yourTable').rows,
i = 0,
l = trs.length,
altValue = true,
currentTr,
tdValue;
while (i) {
i -= 1;
currentTr = trs[i];
tdValue = currentTr.getElementsByTagName('td')[0].innerHTML;
if (tdValue !== currentValue) {
altValue = altValue ? false : true;
}
if (altValue) {
currentTr.className = currentTr.className ?
'alt' : currentTr.className + ' alt';
}
}
精彩评论