4

我在这里有一个典型的 JavaScript 块的示例(将背景样式类应用于表中交替奇数行或偶数行的代码)。我试图在 CoffeeScript 中重写它以尝试学习这一点。CoffeeScript 的范围语法是不同的,而且更像 Ruby 风格。我真的很感激你将如何做到这一点的一个例子?

   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"; 
         }       
       } 
     } 
    }

更新

我正在使用 JQuery 并尝试这样做,但它不起作用(它使所有行#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')
4

4 回答 4

5

您可能还对 jquery 提供的偶数/奇数元选择器感兴趣

$('tbody tr:even').css 'background-color', '#363636'
$('tbody tr:odd').css 'background-color', '#efefef'
于 2010-11-21T03:13:17.177 回答
5

更简洁一点:

for row, i in $('tbody tr')
  color = if i % 2 is 0 then '#363636' else '#efefef'
  $(row).css 'background-color', color
于 2010-11-18T18:37:17.883 回答
1

如果您的最终目标只是对奇数/偶数行应用不同的样式,您可以试试这个:

// CSS file

#myTable tr:nth-child(even) { background-color: #363636; }
#myTable tr:nth-child(odd)  { background-color: #efefef; }

这里没有 JS,只有普通的 CSS,这很好,因为样式是一个演示问题。

但是它只适用于(相对)现代浏览器:IE 9+、Firefox 4+、Chrome...

于 2012-09-13T06:42:23.013 回答
0

Try for row, i in rows,其中i保存循环计数器。

于 2010-11-18T18:28:36.410 回答