How could you write a string function variable using a module in CoffeeScript?

I have an example of a typical JavaScript snippet (code that would apply a background style class to an alternating odd or even row in a table). I am trying to rewrite this in CoffeeScript, trying to find out. The CoffeeScript range syntax is different and more Ruby-esque. I would 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"; 
         }       
       } 
     } 
    }

Refresh

I use jQuery and try to do this, but it does not work (it does all #efefef lines):

$(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')
+3
source share
4 answers

A bit more concise:

for row, i in $('tbody tr')
  color = if i % 2 is 0 then '#363636' else '#efefef'
  $(row).css 'background-color', color
+5
source

/ -, jquery

$('tbody tr:even').css 'background-color', '#363636'
$('tbody tr:odd').css 'background-color', '#efefef'
+5

If your ultimate goal is to simply apply a different style to the odd / even lines, you can try the following:

// 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 style is a presentation issue.

However, it only works in (relatively) modern browsers: IE 9+, Firefox 4+, Chrome ...

+1
source

Try for row, i in rowswhere it icontains a loop counter.

0
source

Source: https://habr.com/ru/post/1775697/


All Articles