How would you write an alternating row function using modulus in CoffeeScript?
-
26-09-2019 - |
문제
I've got an example here of a typical chunk of JavaScript (code that would apply a background style class to an alternating odd or even row in a table). I'm trying to rewrite this in CoffeeScript in my attempt to learn that. The CoffeeScript range syntax is different and more Ruby-esque. I'd really appreciate an example of how you would do this?
function alternate(id){
if(document.getElementsByTagName){
var table = document.getElementById(id);
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
//manipulate rows
if(i % 2 == 0){
rows[i].className = "even";
}else{
rows[i].className = "odd";
}
}
}
}
Update
I'm using JQuery and trying this but it doesn't work (it makes all rows #efefef):
$(document).ready ->
rowCount = $('tbody tr')
for row in rowCount
if row.length % 2 == 0
$('tbody tr').css('background-color', '#363636')
else
$('tbody tr').css('background-color', '#efefef')
해결책
A little more concise:
for row, i in $('tbody tr')
color = if i % 2 is 0 then '#363636' else '#efefef'
$(row).css 'background-color', color
다른 팁
You may also be interested in the even / odd meta selectors provided by jquery
$('tbody tr:even').css 'background-color', '#363636'
$('tbody tr:odd').css 'background-color', '#efefef'
If your end goal is just to apply a different style to odd/even rows, you can try this:
// CSS file
#myTable tr:nth-child(even) { background-color: #363636; }
#myTable tr:nth-child(odd) { background-color: #efefef; }
No JS here, just plain CSS, which is good since styling is a presentation concern.
However it only works in (relatively) modern browsers: IE 9+, Firefox 4+, Chrome...
Try for row, i in rows
, where i
holds the loop counter.