2010-07-16 65 views
0

我们有一个带有say(nxm矩阵)的简单表格,用户将根据以下条件随机选择一组条目。如何单独或作为一组切换单元格颜色

我们的布局是这样的(只是伪代码)

<table> 
    <thead> 
     <tr> 
      c:forEach 1...31 
      <th></th> 
     </tr> 
    </thead> 

    <tbody> 
     <tr> // could be 30 | 40 | 50 rows 
      <td>1...31</td> // Just mentioned that there would be as much cells as looped on the c:forEach above 
     </tr> 
    </tbody> 
</table> 

一]在电池的选择,我们想翻转蓝色,黄色的单元格颜色(即)。颜色应该在特定的单元格选择上切换。 b]如果用户选择标题面板(例如1 ... 31之间的任何值),相应的列(即该列中的所有单元格)应在蓝色,黄色之间切换

我们正在考虑使用不可见复选框来执行此操作,但我们没有得到JavaScript(我们使用jquery)逻辑来选择并正确取消选择。这里需要指针来实现这个功能。

回答

1

你可以做这样的事情,加入适量的CSS类后:

处理细胞:

$('table#yourtable').find('tbody td').click(function(){ 
    $(this).toggleClass('yellow'); 
    // flip yellow on or off 
    // you can figure out how to deal with other states 
}); 

处理列:

$('table#yourtable').find('thead th').click(function(){ 
    var col = $(this).prevAll().length; // had siblings, should be prevall 
    $('table#yourtable').find('tbody tr').each(function(){ 
     $(this) 
      .find('td:eq('+col+')') // nth column 
      .removeClass('yellow blue neutral') // reset colors 
      .addClass('green'); // add a color 
    }); 
}); 

没有测试,这无疑能进一步优化,但它应该给你一些想法。

+0

这不会返回正确的值:'var col = $(this).siblings()。length + 1;'。兄弟姐妹看起来是一个元素的两面。如果我点击第2列10列,则返回10,而不是2. – 2010-07-16 05:11:05

+0

是的,你有我。将其更新为prevall。 – 2010-07-16 05:13:03

+0

不挑剔,但你也错过'.find('td:eq(col)')'上的连接。不知道是否在编辑之前,或者我第一次错过了它。 – 2010-07-16 05:21:00

1

jQuery是一个伟大的库。您可以使用nth-child()选择器来检索列等内容。东西可能是这样的:

$('table thead th').click(function() { 
    // Quick access to the index of this column. 
    // Add an extra 1 to this because later nth-child is 1-indexed. 
    var idx = $(this).prevAll('th').size() + 1; 

    $('table tbody tr td:nth-child(' + idx + ')').css({ 
    'background-color': 'green' 
    }); 
}) 

作为一般的方法。我不知道你想要什么类型的逻辑处理以及你的颜色适合哪里,但这应该有所帮助。