如何单独或作为一组切换单元格颜色

时间:2010-07-16 04:40:20

标签: jquery html css user-interface

我们有一个简单的表格(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>

a]在细胞选择上,我们想要将细胞颜色(即)在蓝色,黄色之间翻转。颜色应在特定单元格选择上切换。 b]如果用户选择标题面板(例如1到31之间的任何内容),相应的列(即该列中的所有单元格)应在蓝色,黄色之间切换

我们正在考虑使用隐形复选框来执行此操作,但我们没有使用javascript(我们使用jquery)逻辑来正确选择和取消选择。需要指点,以实现此功能。

2 个答案:

答案 0 :(得分: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'
  });
})

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

答案 1 :(得分: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
    });
});

未经测试,毫无疑问,这可以进一步优化,但它应该给你一些想法。